我正在尝试抓取一个不使用类或ID的网站,结构如下:
<div>
<div>
<div>
Some content
</div>
</div>
<div>
Other content
<div>
</div>
我正在尝试类似
doc.css('div div')
的内容,但这会返回内容的重复项,因为嵌套容器都与该选择器匹配。
如何仅选择巢的底部,并且知道它们的深度不一样?
问题的另一种表达方式是,有没有办法做类似“没有 div 子项的 div”之类的事情?它可能有其他孩子,只是没有div
编辑:
试图澄清,通过上面的 html 我可以调用:
doc.css('div div').map(&:text)
获取文档的文本,按div分成数组。问题是,该行返回“Some content”两次,因为即使它在 html 中存在一次,但有两个“div div”与该文本匹配。
// will be used to store all the leaves
const leaves = [];
// uses recursion to find all the leaves
const findLeaves = ($branch) => {
if ($branch.children.length === 0)
{
leaves.push($branch);
return;
}
[...$branch.children].forEach(($branch) => findLeaves($branch));
};
// parent element of elements you want to search through
const $branch = document.querySelector("body > div");
// initiate finding leaves
findLeaves($branch);
// remove from all the leaves non divs
const what_you_want = leaves.filter(($leaf) => $leaf.tagName === "DIV");
console.log(what_you_want);