尝试遍历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)
虽然这个问题缺少一些细节,但是一个用于遍历未知级别的树状结构的强大工具是递归:
function processData (product) {
if(product.length) {
const productChildrem = product[0].childNodes;
// process this node
productChildrem.forEach(function (child) {
return processData(child)
});
}
通过对每个孩子的重复函数调用,您最终将处理所有这些孩子。
如果你想要自己的Microdata解析器,那么你可以从这样的东西开始。当然,你需要详细说明。例如,某些属性是array
s等。
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));
});