如何使用Cheerio筛选含指定关键词aria-label的<a>标签?
如何用Cheerio检测标签aria-label属性中的关键词?
我正在开发一款基于关键词(如"environment"、"climate")抓取新闻网站数据的爬虫,但最近遇到一个网站,无法通过检查标签文本的方式筛选目标关键词。该网站的标签HTML结构如下:
<a aria-label="Ravaged by floods, Bangladesh pitches plan to adapt to climate impacts" class="card-with-image-zoom" href="https://en.prothomalo.com/environment/climate-change/ravaged-by-floods-bangladesh-pitches-plan-to-adapt-to-climate-impacts">
我此前使用Cheerio筛选关键词的代码如下:
const html = response.data; const $ = cheerio.load(html); const specificarticles = []; $('a:contains("climate"),a:contains("environment")', HTML)
请问如何使用Cheerio检测该HTML结构中标签aria-label属性内的关键词?
解决方案
Cheerio支持通过属性选择器或filter()方法结合正则来筛选包含指定关键词的aria-label属性,以下是两种实用方案:
方案一:使用CSS属性包含选择器
直接用[aria-label*="关键词"]选择器匹配属性值包含指定子串的标签,写法简洁:
const html = response.data; const $ = cheerio.load(html); const specificarticles = []; // 筛选aria-label包含"climate"或"environment"的<a>标签 const targetLinks = $('a[aria-label*="climate"], a[aria-label*="environment"]'); // 遍历结果提取数据 targetLinks.each((index, element) => { specificarticles.push({ href: $(element).attr('href'), ariaLabel: $(element).attr('aria-label') }); });
方案二:使用filter()配合正则表达式
如果需要更灵活的匹配规则(比如忽略大小写、匹配完整单词),可以用正则配合filter()方法:
const html = response.data; const $ = cheerio.load(html); const specificarticles = []; // 正则匹配,i标记表示忽略大小写 const keywordRegex = /climate|environment/i; // 筛选符合条件的<a>标签 const targetLinks = $('a').filter((index, element) => { const ariaLabel = $(element).attr('aria-label'); // 确保aria-label存在且匹配正则 return ariaLabel && keywordRegex.test(ariaLabel); }); // 提取所需数据 targetLinks.each((index, element) => { specificarticles.push({ href: $(element).attr('href'), ariaLabel: $(element).attr('aria-label') }); });
内容的提问来源于stack exchange,提问作者Mohammad Mustak Absar Khan
相关产品推荐
相关产品推荐

