我正试图用node.js构建一个scraper,它将允许我从大量的域名中提取新闻标题(它们都是不同的,所以我必须在我的方法中尽可能的通用)。目前,我在python中已经有了一个有效的实现,它利用Beautiful soup和regex允许我定义一组关键字,并返回包含这些关键字的标题。下面是一段相关的python代码。
for items in soup(text=re.compile(r'\b(?:%s)\b' % '|'.join(keywords)))
为了说明预期的输出,让我们假设有一个包含新闻文章的域(Bellow是一个包含标题的html片段)。
<a class="gs-c-promo-heading gs-o-faux-block-link__overlay-link gel-pica-bold nw-o-link-split__anchor" href="/news/uk-52773032"><h3 class="gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text">Time to end Clap for Carers, says founder</h3></a>
给定一个关键字的预期输出 时间 将是一个带有标题的字符串 是时候结束为照顾者鼓掌了
我的问题是:是否可以用cheerio做类似的事情?要在nodejs中实现同样的结果,最好的方法是什么?
EDIT:现在我可以用这个方法了。在匹配标题的基础上,我还想提取帖子的URLs
function match_headlines($) {
const keywords = ['lockdown', 'quarantine'];
new RegExp('\\b[A-Z].*?' + "(" + test_keywords.join('|') + ")" +
'.*\\b', "g");
let matches = $('a').map((i, a) => {
let links = $(a).attr('href');
let match = $(a).text().match(regexPattern);
if (match !== null) {
let posts = {
headline: match['input'],
post_url: links
}
return posts
}
})
return matches.filter((x) => x !== null)
}
也许像这样。
let re = new Regexp('\\b' + keywords.join('|') + '\\b')
let texts = $('a h3').map((i, a) => $(a).text())
let headlines = texts.filter(text => text.match(re))