node.js Cheerio / jquery 选择器:如何获取嵌套 div 中的元素列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32655076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cheerio / jquery selectors: how to get a list of elements in nested div's?
提问by MarcoS
I need to parse some markup similar to this one, from an html page:
我需要从 html 页面解析一些与此类似的标记:
<div id="list">
<div class="item-level-a">
<div class="item-level-b">
<a href="http://www.example.com/1"></a>
</div>
</div>
<div class="item-level-a">
<div class="item-level-b">
<a href="http://www.example.com/2"></a>
</div>
</div>
<div class="item-level-a">
<div class="item-level-b">
<a href="http://www.example.com/3"></a>
</div>
</div>
</div>
I did try with this code:
我确实尝试过使用此代码:
$list = [];
$('div[id="list"]').each(function() {
var href = $(this).find('div > div > a').attribs('href');
list.push(href);
});
without success: error was:
没有成功:错误是:
TypeError: Object <a href="http://www.example.com/1"></a>
<a href="http://www.example.com/2"></a>
<a href="http://www.example.com/3"></a>
has no method 'attribs'
:-(.
:-(。
Any clue?
有什么线索吗?
回答by Trott
In cheerioand jquery, you get attributes with attr(), not attrib().
在cheerioand 中jquery,您可以使用attr(),而不是获得属性attrib()。
There are a few other problems with your code. Here is a working version using cheerio. It probably works in jquerythis way as well.:
您的代码还有一些其他问题。这是一个使用cheerio. 它也可能以jquery这种方式工作。:
var list = [];
$('div[id="list"]').find('div > div > a').each(function (index, element) {
list.push($(element).attr('href'));
});
console.dir(list);
回答by sdgfsdh
For those who prefer a functional style:
对于那些喜欢功能性风格的人:
const list = $('div[id="list"]')
.find('div > div > a')
.toArray()
.map(element => $(element).attr('href')));

