Puppeteer:如何监听 innerHTML 的变化 [英] Puppeteer: how to listen for on innerHTML change

查看:111
本文介绍了Puppeteer:如何监听 innerHTML 的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个聊天应用,其状态由这一行表示:

I have a chat app with status represented by this line:

<span id='status'>Offline</span> 

并且我希望 Puppeteer 在每次此范围内的文本更改时都进行记录.

and I want Puppeteer to log every time the text within this span changes.

比如说,一开始状态是离线",然后变成在线",一段时间后变成离开"等等.我想让 Puppeteer 捕捉那些瞬间和状态(离线>在线>离开)

Say, in the beginning the status was "Offline", then it was changed to "Online", and then after some time to "Away" and so on. I want Puppeteer to capture those moments and the status (Offline>Online>Away)

我设法做的是以下内容:

What I managed to do is the following:

const page = await browser.newPage();
await page.goto('https://chat.com');
const statusHandle = await page.$('span#status');
let statusText = await page.evaluate(() => document.querySelector('#status').innerText);
let iniVal = {statusHandle,statusText };

此时我有 statusHandle 和初始状态.

at this point I have the statusHandle and the initial status.

现在,我的理解(根据 12) 是我需要将两者结合在

Now, my understanding (as per 1 and 2) is that I need to combine the two in

await page.waitForFunction(
  (iniVal) => iniVal.statusHandle.innerHTML !== iniVal.statusText, 
  { timeout: 0 }, 
  iniVal
) 

并将其放入循环中.这就是我挣扎的重点.

and place it in a loop. That's the point, where I'm struggling.

首先它给出了一个类型错误TypeError: Converting circle structure to JSON",这是由于传递的键值对不是基元,但即使我过度简化并且只是这样做(根据 1):

First it gives a type error "TypeError: Converting circular structure to JSON", which is due to the passed key value pairs not being primitives, but even when I oversimplify and just do (as per 1):

await page.waitForFunction(
  'document.querySelector("span#status").inner‌​Text === "Online"'
)

它什么也没产生.

总结:我期待

  1. 让 Puppeteer 评估 document.querySelector('#status').innerText !== statusText

返回新的状态值

让流程循环运行

推荐答案

我只是设置了一个带有回调的递归函数:

I'd just set a recursive function with a callback:

async function monitor (selector, callback, prevValue) {
  const newVal = await page.$(selector);
  if (newVal !== prevValue) {
    callback(newVal);
  }
  /* add some delay */
  await new Promise(_ => setTimeout(_, 1000))
  /* call recursively */
  monitor (selector, callback, newVal);
}

monitor('span#status', status => {
  // Fires whenever `status` changes
})

这篇关于Puppeteer:如何监听 innerHTML 的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆