Cheerio中如何解析嵌套div下所有同名class的div并获取style属性
问题根源
原代码无法拿到全部结果的原因有两个:
- Cheerio的
.attr()方法只会返回匹配元素集合中第一个元素的对应属性值,不会自动遍历所有匹配节点返回属性集合 - 原逻辑仅遍历了
.classParent层级,没有单独遍历每个父节点下的.class1元素,直接查找子级.class2后取attr,自然只能拿到第一个值
正确实现代码
你描述的单层级集合用{ "style attribute value", "style attribute value" }的写法不符合JavaScript语法,以下实现用数组存储同层级下所有.class2的style属性,最终返回结构完全匹配你的预期:
const prop = [] // 遍历所有父级下的.class1元素,每个元素对应结果数组中的一项 $('.classParent .class1').each((_, class1El) => { const currentStyleGroup = [] // 遍历当前.class1下的所有.class2元素 $(class1El).find('.class2').each((_, class2El) => { const style = $(class2El).attr('style') if (style) currentStyleGroup.push(style) }) prop.push(currentStyleGroup) })
返回结果结构
运行后得到的prop结构如下,和你预期的层级完全对应:
[ ["width: 10px; height: 10px", "color: red", ...], // 第1个.class1下所有.class2的style集合 ["margin: 0", "display: flex", ...], // 第2个.class1下所有.class2的style集合 ["font-size: 14px", ...], // 第3个.class1下所有.class2的style集合 // ... ]
如果你确实需要对象格式的单层级集合,只需要把push到数组的逻辑改为给对象赋值即可,比如用.class2的索引作为对象键名。
内容的提问来源于stack exchange,提问作者Jimmy
相关产品推荐
相关产品推荐

