【问题标题】:Puppeteer - update content of a scraped websitePuppeteer - 更新抓取网站的内容
【发布时间】:2021-03-13 11:54:49
【问题描述】:

我想使用 nodejs 创建一个 cli 脚本来抓取不提供 api 的体育结果网站的内容。我知道如何管理内容抓取,但我有疑问。如果结果会发生变化并将其显示在终端窗口中的表格中,是否可以更新抓取的内容??

【问题讨论】:

    标签: javascript node.js web-scraping command-line-interface puppeteer


    【解决方案1】:

    这是一个简化的示例。该脚本打开https://time.is/,并在每次更改站点时钟元素时将时间记录到控制台。它使用page.exposeFunction()MutationObserver

    import puppeteer from 'puppeteer';
    
    const browser = await puppeteer.launch();
    
    try {
      const [page] = await browser.pages();
    
      await page.goto('https://time.is/');
      await page.exposeFunction('updateTime', updateTime);
    
      await page.evaluate(() => {
        const clock = document.querySelector('#clock0_bg');
    
        const config = { subtree: true, childList: true, attributes: true, characterData: true };
        const callback = function () { window.updateTime(clock.innerText); };
        const observer = new MutationObserver(callback);
        observer.observe(clock, config);
      });
    } catch (err) { console.error(err); }
    
    function updateTime(time) {
      console.log(time);
    }
    

    【讨论】:

    • 感谢您的帮助,我将从您的示例开始处理我的代码!只需注意 baout sn-p,是否可以在不使用异步 IIFE 的情况下使用 await?
    • 如果你使用最后一个带有 ES 模块的 Node.js(.mjs 文件扩展名),那么可以。
    • 不,我使用的是传统的.js 文件,所以我认为在使用 puppeteer 之前我需要使用 IIFE 包装器。我要抓取的网站(diretta.it)正在使用 react 或 angular(我不知道)来生成 dom,所以我需要找到每个元素的类而不是应用你的 sn-p
    猜你喜欢
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多