You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Puppeteer抓取每秒更新的动态网页数据

解决方案

你可以将重复执行的逻辑封装为异步函数,通过定时器每秒调用即可,完整可运行代码如下:

const cheerio = require('cheerio');
const puppeteer = require("puppeteer")

const dataUrl = 'https://time.is/';

(async () => {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto(dataUrl);

  // 封装单次数据拉取、解析逻辑
  const getCurrentTime = async () => {
    const pageData = await page.evaluate(() => {
      return { html: document.documentElement.innerHTML }
    }) 
    const $ = cheerio.load(pageData.html)
    console.log($('#clock').text())
  }

  // 首次立即执行
  await getCurrentTime()
  // 每秒执行一次
  setInterval(getCurrentTime, 1000)
})()

如果担心网络波动导致异步任务堆积,你可以改用递归setTimeout的写法,确保上一次拉取解析完成后再间隔1秒执行下一次:

// 将上面的setInterval替换为以下逻辑即可
const loopGetTime = async () => {
  await getCurrentTime()
  setTimeout(loopGetTime, 1000)
}
loopGetTime()

内容的提问来源于stack exchange,提问作者kafaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:36:04