node.js - 如何使用cheerio仅从html链接中获取文本
问题描述
您好,我有一个网页,其中包含这样的 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>
我想要这样的结果
美国可能正处于新的Covid激增的风口浪尖
出售世界上“最危险”奶酪的意大利人最高可被罚款6万美元
《蒙面歌王》揭开凤凰的身份
这是我尝试过的
var list = [];
$('div[class="css-6f9"]').find('div > a').each(function (index, element) {
list.push($(element).attr('href'));
});
console.log(list);
结果是空数组
我在这里是全新的,不知道如何获取<a></a>
标签中的结果请帮助
解决方案
尝试这个
不需要cheerio
作为$
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)));
推荐阅读
- azure-devops - 从 Spinnaker 触发 Azure DevOps 发布管道阶段
- php - 联系表格不断重定向到 php 页面
- bash - 如何在 curl 标头中连接时间戳?
- html - XHTML 元素“元”不允许作为子元素
- macos - Xamarin.Forms 支持的最低 MacOS 版本是多少?
- reactjs - 从选择中选择时不显示选定的菜单项
- node.js - NodeJs tcp 套接字接收块
- python-3.x - 您如何获取一个涵盖多年的数据框,并将其分解为每年的单独 DF
- excel - 复制和粘贴整个行和合并行的脚本?
- bash - 改变进程的nice值