javascript - 循环遍历 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)
解决方案
虽然这个问题缺少一些细节,但遍历树状结构的未知级别的一个强大工具是递归:
function processData (product) {
if(product.length) {
const productChildrem = product[0].childNodes;
// process this node
productChildrem.forEach(function (child) {
return processData(child)
});
}
通过对每个孩子的重复函数调用,您最终将处理所有孩子。
推荐阅读
- r - 在 R 的数据框中填充反应列
- asp.net-mvc - 5 个 MVC webApps 共享相同的报告程序集(5 次)
- fortran - Fortran sin 和 cos 的双精度
- laravel - Laravel 7 - 如何在登录时更改数据库?
- javascript - 使用 Python 创建/编辑 mxgraph 模型
- database - 关于数据库设计:我应该如何对一些日期信息进行分类?
- python - 在seaborn中具有不同y轴和不同y尺度的箱线图
- .net - NET Core - FromQuery Datetimeoffset 不允许 +/- 符号
- nginx - 如何根据 url 参数更改 Nginx 中的别名?
- sql - 如何在sql server新版本中使用域完整性约束和断言约束