【问题标题】:Node.js Cheerio Live Update/Instant Refresh page on every HTML body change每次 HTML 正文更改时的 Node.js Cheerio 实时更新/即时刷新页面
【发布时间】:2022-02-04 15:36:08
【问题描述】:

我正在使用 Axioscheerio 来抓取板球比分网站并将其数据转换为 JSON 格式。 但问题是分数和其他信息不会在我的 API 响应中立即更新。 我想在我的快递服务器中拥有一种 useEffect(我知道,它是 React Hook 并且在 Express 中不起作用)功能,这样每当主网站上的分数发生变化时,我的服务器就会重新抓取页面并显示更新的数据。

axios(link).then(response => {
        const html = response.data
        const $ = cheerio.load(html)
        const score = []

        $('.scorecard-container', html).each(function(){
            const title = $(this).text()
            const url = link + $(this).find('a').attr('href')
            score.push({
                id: score.length + 1,
                title,
                url
            })
        })
        res.json(score)
    }).catch(err => {res.send('Something went wrong'); console.log(err)})

在此先感谢 :)

【问题讨论】:

  • 这个问题真的没有意义,因为cheerio 不是浏览器,它只是一个解析器。
  • 我只是问如何重新解析更新的信息
  • 你会提出一个新的请求并以同样的方式进行
  • 我该怎么办?我应该使用递归还是可以通过其他方法来完成?
  • 为什么需要递归?

标签: javascript node.js api express cheerio


【解决方案1】:

示例快递端点

get("/stats", async (req, res) => {
  let { data } = await axios.get(someUrl)
  let $ = cheerio.load(data)
  res.json({
    title: $('title').text()
  })
})

反应中

useEffect(() => {
  fetch("/stats").then(r=> r.json().then(data => setStats(data)))
}, [])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多