首页 > 解决方案 > 从 /r/GameDeals 中抓取包含 discord.js 中“免费”一词的标题 + 链接?

问题描述

总的来说,我对 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 类的理解非常有限,并且添加“包含单词:免费”的过滤器是一个完整的“另一个故事”。

任何指导将不胜感激。

我正在使用 puppeteer,但有人建议我尝试通过使用“reddit.com/r/GameDeals.json”来使用 Reddit 的 JSON API,但我不确定如何开始。

标签: node.jsdiscord.jspuppeteerreddit

解决方案


如果您只想查找包含“免费”一词的链接,则需要过滤您拥有的节点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);

推荐阅读