首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用cheerio只从html链接中获取文本

如何使用cheerio只从html链接中获取文本
EN

Stack Overflow用户
提问于 2021-03-19 08:41:43
回答 1查看 279关注 0票数 0

你好,我有一个网页,里面有这样的HTML

代码语言:javascript
复制
<div class="css-content">
   <div class="css-2aj">
      <img src="" >
      <div data-bn-type="text" id="/48" class="">Latest News</div>
   </div>
   <div class="css-6f9">
      <div class="css-content">
         <a data-bn-type="link" href="/en/blog/news/523hshhshhshhs3331adc0" class="css-1ej">US could be on cusp of new Covid surge</a>

         <a data-bn-type="link" href="/en/blog/news/423hshhshhshhs3331adc0" class="css-1ej">Stop sharing your vaccine cards on social media</>
            <a data-bn-type="link" href="/en/blog/news/2222hshhshhshhs3331adc0" class="css-1ej">Italians can be fined up to $60,000 for selling the world's 'most dangerous' cheese</a>

         <a data-bn-type="link" href="/en/blog/news/2223hshhshhshhs3331adc0" class="css-1ej">The Masked Singer' reveals the identity of The Phoenix<a/>

        
      </div>
   </div>
</div>

我想要这样的结果

  • US可能正处于新的Covid激增

的尖端

  • 意大利人出售世界上最危险的奶酪

,最高可被罚款6万美元

戴面具的歌手

  • ‘揭示了凤凰

的身份

这就是我试过的

代码语言:javascript
复制
    var list = [];
$('div[class="css-6f9"]').find('div  > a').each(function (index, element) {
    list.push($(element).attr('href'));
});


console.log(list);

结果是空数组。

我在这里是全新的,不知道如何获取<a></a>标签中的结果--请帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-19 09:00:38

尝尝这个

不需要cheerio作为$

代码语言:javascript
复制
const html = `<div class="css-content">
<div class="css-2aj">
   <img src="" >
   <div data-bn-type="text" id="/48" class="">Latest News</div>
</div>
<div class="css-6f9">
   <div class="css-content">
      <a data-bn-type="link" href="/en/blog/news/523hshhshhshhs3331adc0" class="css-1ej">US could be on cusp of new Covid surge</a>

      <a data-bn-type="link" href="/en/blog/news/423hshhshhshhs3331adc0" class="css-1ej">Stop sharing your vaccine cards on social media</>
         <a data-bn-type="link" href="/en/blog/news/2222hshhshhshhs3331adc0" class="css-1ej">Italians can be fined up to $60,000 for selling the world's 'most dangerous' cheese</a>

      <a data-bn-type="link" href="/en/blog/news/2223hshhshhshhs3331adc0" class="css-1ej">The Masked Singer' reveals the identity of The Phoenix<a/>

     
   </div>
</div>
</div>`;
const cheerio = require('cheerio');
const $ = cheerio.load(html);
let list = [];
$('.css-content > a').each(function () {
  list.push($(this).text().trim());
});
console.log(list.filter((item) => Boolean(item)));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66704958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档