尝试循环访问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)发布于 2019-04-10 01:23:56
虽然这个问题缺少一些细节,但用于遍历树状结构的未知层次的一个强大工具是递归
function processData (product) {
if(product.length) {
const productChildrem = product[0].childNodes;
// process this node
productChildrem.forEach(function (child) {
return processData(child)
});
}通过对每个子级的重复函数调用,您最终将处理所有这些子级。
发布于 2019-04-10 04:55:34
如果你想要自己的Microdata解析器,那么你可以从下面这样开始。当然,你需要对它进行大量的阐述。例如,某些属性是array等。
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));
});https://stackoverflow.com/questions/55598081
复制相似问题