Cheerio:如何获得祖父母下的所有标签
Cheerio: How to get all tags under a grandparent
我想从指定的 parent 标签中获取任意级别嵌套兄弟项下的所有 img
标签,但我的实现没有打印出任何 el
.
<div class='grand'>
<div>
<img src='1.png'>
</div>
<div>
<div>
<img src='2.png'>
</div>
</div>
<img src='3.png'>
</div>
到目前为止我的实施:
let images = $('div.grand').siblings().find('img')
images.each((i, el) => {
console.log($(el).html()) //prints empty string
})
基本上,我想获得与 python 中 BeautifulSoup
的 soup.findAll('img')
相同的结果。
您的代码不会打印出空字符串 - 它不会在 each
中打印 任何内容,因为没有匹配的元素。
要查找与某个选择器匹配的元素,这些元素是与另一个选择器匹配的元素的后代,请在它们之间放置 space。在这里,对于从 .grand
继承的 img
,您将使用 .grand img
:
$('.grand img').each((i, el) => {
console.log(el.attribs.src)
});
结果:
1.png
2.png
3.png
你很接近!执行您需要的操作:
$(".grand img").each(function() {
const src = $(this).attr("src")
console.log(src)
})
这利用 $(this)
访问引用对象的 src
属性
.grand img
表示访问 class 为 grand
的元素内的所有子元素
我想从指定的 parent 标签中获取任意级别嵌套兄弟项下的所有 img
标签,但我的实现没有打印出任何 el
.
<div class='grand'>
<div>
<img src='1.png'>
</div>
<div>
<div>
<img src='2.png'>
</div>
</div>
<img src='3.png'>
</div>
到目前为止我的实施:
let images = $('div.grand').siblings().find('img')
images.each((i, el) => {
console.log($(el).html()) //prints empty string
})
基本上,我想获得与 python 中 BeautifulSoup
的 soup.findAll('img')
相同的结果。
您的代码不会打印出空字符串 - 它不会在 each
中打印 任何内容,因为没有匹配的元素。
要查找与某个选择器匹配的元素,这些元素是与另一个选择器匹配的元素的后代,请在它们之间放置 space。在这里,对于从 .grand
继承的 img
,您将使用 .grand img
:
$('.grand img').each((i, el) => {
console.log(el.attribs.src)
});
结果:
1.png
2.png
3.png
你很接近!执行您需要的操作:
$(".grand img").each(function() {
const src = $(this).attr("src")
console.log(src)
})
这利用 $(this)
访问引用对象的 src
属性
.grand img
表示访问 class 为 grand