如何用Cheerio选择根元素直接子元素?选中失败求解决方案
Cheerio 选择根元素及直接子元素的解决方案
选中外层根div(<div 1>)
Cheerio 加载 HTML 片段时,不会自动将你的外层 div 设为默认上下文,直接用 :scope 或 >div 无法定位。正确的做法是通过根节点获取:
// 获取根节点的第一个子元素,也就是你要的外层div const rootDiv = $.root().children().first();
如果你的 HTML 片段中外层只有这一个 div,也可以简化为:
const rootDiv = $('div').first();
选中根div的直接子元素<div 2>
拿到根 div 后,直接用 children() 方法获取它的直接子元素,再通过 eq(1) 选中第二个(索引从0开始计数):
// 先获取根div,再选第二个直接子div const div2 = rootDiv.children().eq(1); // 链式调用写法 const div2 = $.root().children().first().children().eq(1);
为什么之前的方法无效?
:scope在 Cheerio 中需要结合上下文使用,直接调用$(':scope')时,上下文是整个文档根,而非你加载的外层 div,所以返回 null。>div是直接子选择器,直接使用时默认相对于文档根(通常是<body>),而你的外层 div 是<body>的子元素,所以无法匹配到它的子元素。
内容的提问来源于stack exchange,提问作者Jeanluca Scaljeri
相关产品推荐
相关产品推荐

