解析模式微数据并像Google数据结构一样排列它们

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

感恩节快乐:)

我正在学习Javascript和Dom,我想从HTML解析schemadata并像Google数据结构一样激怒。

*模式数据信息

<div itemscope itemtype="http://www.schema.org/Product">

  <div itemscope itemtype="http://www.schema.org/Person">
  <span itemprop="birthday" datetime="2009-05-10">May 10th 2009</span>
  </div>

  <div itemprop="name"> Product name </div>
  <div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
    <span itemprop="price" content="500.00"> USD 500 </span>
  </div>

</div>

* Google数据结构Google data structure

我的问题是,

首先,要解析顶级类别“产品”和“人”,如何使用Javascript和DOM选择包含属性“ [itemtype]”但属性为“ [itemprop]”的节点?

第二,由于Person节点是Product的子节点,因此很难排除顶级类别的子节点。如果选择类别节点,如何排除另一个类别的子节点?在这种情况下,我想在排列类别时排除类别节点。

我从搜索中找到了此代码段,但是,这对我想要的Google无效。

var result = {};
var items = [];
document.querySelectorAll("[itemscope]")
  .forEach(function(el, i) {
    var item = {
      "type": [el.getAttribute("itemtype")],
      "properties": {}
    };
    var props = el.querySelectorAll("[itemprop]");
    props.forEach(function(prop) {
      item.properties[prop.getAttribute("itemprop")] = [
        prop.content || prop.textContent || prop.src
      ];
      if (prop.matches("[itemscope]") && prop.matches("[itemprop]")) {
        var _item = {
          "type": [prop.getAttribute("itemtype")],
          "properties": {}
        };
        prop.querySelectorAll("[itemprop]")
          .forEach(function(_prop) {
            _item.properties[_prop.getAttribute("itemprop")] = [
              _prop.content || _prop.textContent || _prop.src
            ];
          });
        item.properties[prop.getAttribute("itemprop")] = [_item];
      }
    });
    items.push(item)
  })

result.items = items;

console.log(result);

document.body
  .insertAdjacentHTML("beforeend", "<pre>" + JSON.stringify(result, null, 2) + "<pre>");

var props = ["Blendmagic", "ratingValue"];

// get the 'content' corresponding to itemprop 'ratingValue' 
// for item prop-name 'Blendmagic'
var data = result.items.map(function(value, key) {
  if (value.properties.name && value.properties.name[0] === props[0]) {
    var prop = value.properties.reviews[0].properties;
    var res = {},
      _props = {};
    _props[props[1]] = prop[props[1]];
    res[props[0]] = _props
    return res
  };
})[0];

console.log(data);
document.querySelector("pre").insertAdjacentHTML("beforebegin", "<pre>" + JSON.stringify(result, null, 2) + "<pre>");

我应该使用XPATH代替DOM吗?

非常感谢大家:)

javascript dom xpath schema microdata
1个回答
0
投票

我刚刚实现了一个最有效的解决方案。

选择器的一个问题是我无法解决如何仅获取下一级属性的问题。例如一开始,您只需要顶级itemscope,然后希望itemprops直接位于每个等内部。

我最终手动解析了DOM。即逐个元素地递归地遍历子级。

我走的时候,我一直在跟踪与当前正在处理的对象有关的上下文。找到属性后,便向其中添加属性。

如果我碰到另一个itemscope,那么我将创建一个新的内部对象,并使用该对象解析该范围。

然后我确定了如何执行itemid和itemref!

© www.soinside.com 2019 - 2024. All rights reserved.