【问题标题】:How to get specific parts of a page using cheerio如何使用cheerio获取页面的特定部分
【发布时间】:2019-09-04 12:35:12
【问题描述】:

所以,我正在尝试制作一个 discordbot,以每 x 次检查一次游戏是否在某人的愿望清单上打折。但我无法让cheerio 阅读页面的某些属性。例如,如果我记录“.wishlist_row”,它将是空日志。此外,当我尝试记录整个页面文本时,它不会记录游戏名称和价格......我如何抓取这些数据?

我试过了:

console.log("Starting to log Steam wishlists updates!")
    setInterval(function () {
        request("https://store.steampowered.com/wishlist/id/myusername/#sort=order", async (error, response, html) => {
    if (!error && response.statusCode === 200) {
        const $ = cheerio.load(html);
        console.log($('.wishlist_row').text())
            $('.wishlist_row').each((i, element) => {
                console.log($(element).find('.discount_pct'))
            })
        }
    })
}, 1000)

【问题讨论】:

  • html 参数的值是多少?你确定它是一个 HTML 字符串吗? console.log 出来看看
  • 我做到了,我登录了 html.text(),它只显示了选择语言、帐户名称等内容。但没有关于愿望清单的内容......
  • 在对 HTML 字符串使用 Cheerio 之前,您是否以编程方式登录到相应的帐户?我可能是您在一个没有登录帐户的页面上使用cheerio
  • 我无需登录即可获得 hte 链接,我有自己的愿望清单向所有人开放,因此无需登录即可访问它。
  • 作为 CSS 选择器的测试,您是否能够从同一个 DOM 中进行选择,使用 jQuery 并获得您想要的结果?

标签: node.js discord.js cheerio steam


【解决方案1】:

不幸的是,Cheerio 可以读取网页的源代码,但无法渲染 JavaScript 来创建您在浏览器上看到的完整体验。

当您在浏览器中查看某人的愿望清单时,您看到的愿望清单项目元素是从其他地方获取并使用 JavaScript 呈现的,因此您将无法通过抓取页面的源代码来获取此类信息。

不过,Steam 确实提供了一个公共 API,您可以调用该 API 来获取此数据: https://store.steampowered.com/wishlist/id/{myusername}/wishlistdata/?p=0

使用此 API,您可以像这样访问每个游戏的当前折扣百分比:

console.log("Starting to log Steam wishlists updates!")
    setInterval(function () {
        request("https://store.steampowered.com/wishlist/id/{myusername}/wishlistdata/?p=0", (error, response) => {
            if (!error && response.statusCode === 200) {
                let wishlist = JSON.parse(response.body);

                for (let appid in wishlist) {
                    console.log(wishlist[appid]); // game information
                    console.log(wishlist[appid].subs[0].discount_pct); // discount percentage
                }
            }
        });
}, 1000);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2014-01-04
    相关资源
    最近更新 更多