【问题标题】:Cheerio - Find and print all attributes that match queryCheerio - 查找并打印与查询匹配的所有属性
【发布时间】:2019-07-15 22:02:55
【问题描述】:

如果我有以下 html 代码:

<a class="my-lovely-name" title="hello" href="fb.com">Random stuff</a>
<div class="my-lovel-name" title="ew" href="yb.com">blabla</div>

如何使用cheerio 提取titlehref 的所有值?我尝试了以下方法,但它只会提取 hellofb.com 并跳过其余元素:

console.log($('.my-lovely-name').attr('title')) => should print the titles of all elements with this class
console.log($('.my-lovely-name').attr('href')) => => should print the href-s of all elements with this class

【问题讨论】:

标签: javascript html node.js cheerio


【解决方案1】:

您应该能够将它们映射到一个数组中。

console.log(
  $('.my-lovely-name').map(
    (index, element) => element.title
  ).get()
)

参考。 https://github.com/cheeriojs/cheerio#map-functionindex-element-

【讨论】:

  • 工作就像一个魅力。谢谢你,先生!
【解决方案2】:
$('..my-lovely-name').map((index, element) => {
    const attributes = element.attribs;
    Object.keys(attributes).map(key => {
        console.log(key, ': ', attributes[key]);
    })
});

通过这个,您将获得 html 元素中所有属性的列表,然后您可以过滤您感兴趣的那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2021-11-18
    • 1970-01-01
    • 2017-07-20
    • 2016-07-02
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多