puppeteer 等待页面/DOM 更新 - 响应初始加载后添加的新项目

wiv*_*vku 3 javascript webautomation node.js puppeteer

我想使用 Puppeteer 来响应页面更新。该页面显示项目,当我离开页面打开时,新项目可能会随着时间的推移出现。例如,每 10 秒添加一个新项目。

我可以使用以下内容来等待页面初始加载时的项目:

await page.waitFor(".item");
console.log("the initial items have been loaded")
Run Code Online (Sandbox Code Playgroud)

我怎样才能等待/捕捉未来的物品?我想实现这样的东西(伪代码):

await page.goto('http://mysite');
await page.waitFor(".item");
// check items (=these initial items)

// event when receiving new items:
// check item(s) (= the additional [or all] items)
Run Code Online (Sandbox Code Playgroud)

har*_*ded 5

您可以使用ExposureFunction来公开本地函数:

await page.exposeFunction('getItem', function(a) {
    console.log(a);
});
Run Code Online (Sandbox Code Playgroud)

然后你可以使用page.evaluate创建一个观察者并监听在父节点内创建的新节点。

此示例抓取(这只是一个想法,而不是最终作品)Stack Overflow 中python 聊天,并打印在该聊天中创建的新项目。

var baseurl =  'https://chat.stackoverflow.com/rooms/6/python';
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto(baseurl);

await page.exposeFunction('getItem', function(a) {
    console.log(a);
});

await page.evaluate(() => {
    var observer = new MutationObserver((mutations) => { 
        for(var mutation of mutations) {
            if(mutation.addedNodes.length) {
                getItem(mutation.addedNodes[0].innerText);
            }
        }
    });
    observer.observe(document.getElementById("chat"), { attributes: false, childList: true, subtree: true });
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!MutationObserver 让我走上了正轨。让我找到了另一个有用的例子:https://github.com/GoogleChrome/puppeteer/issues/2945 (2认同)