问题描述
我一般对Javascript和编程都是超级新手,因此我找到了一个渠道,可以在我的实践中使用它并在discord频道中为我和我的朋友共享/创建功能。我正在尝试设置一个刮板,该刮板从/ r / GameDeals subreddit中提取带有包含“免费”一词的链接的标题。到目前为止,通过我在网上找到的资源,我已经能够获得前25个链接:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('https://www.reddit.com/r/GameDeals/',{ waitUntil: 'networkidle0' });
const links = await page.evaluate(async () => {
window.scrollBy(0,document.body.clientHeight);
await new Promise(resolve => setTimeout(resolve,1));
return [...document.querySelectorAll('.scrollerItem div:nth-of-type(2) article div div:nth-of-type(3) a')]
.map((el) => el.href);
});
bot.on('message',msg=>{
if(msg.content === "gamedeals"){
msg.reply(links,links.length);
}
})
await browser.close();
})();
对于要获得所需的特定HTML类,我的了解非常有限,并且添加“包含单词:FREE”的过滤器是一个完整的故事。
任何指导将不胜感激。
我正在使用puppeteer,但是有人建议我通过使用'reddit.com/r/GameDeals.json'尝试使用Reddit的JSON API,但我不确定如何开始。
解决方法
如果您只想查找包含单词“ free”的链接,则需要过滤page.evaluate
中的节点:
[...document.querySelectorAll('.scrollerItem div:nth-of-type(2) article div div:nth-of-type(3) a')] // <-- we've got all the links
.filter((el) => el.innerText.toLowerCase().includes('free') ) // <-- only keep those with word "free"
.map((el) => el.href);