使用 puppeteer 永远抓取同一页面

Scraping the same page forever using puppeteer

正在抓取。如何在不刷新页面的情况下停留在一个页面上,每xx秒读取一次内容来搜索数据?我使用这种方式,但一段时间后电脑崩溃了。关于如何提高效率的任何想法?我想在不使用 while (true) 的情况下实现它。 readOdds 函数并不总是延迟相同的时间。

//...
while(true){
   const html = await page.content();
   cant = await readOdds(html); // some code with the html
   console.info('Waiting 5 seconds to read again...');
   await page.waitFor(5000);
}

这是一个部分

async function readOdds(htmlPage){
    try {
        var savedat = functions.mysqlDateTime(new Date());
        var pageHtml=htmlPage.replace(/(\r\n|\n|\r)/gm,"");
        var exp_text_all = /<coupon-section(.*?)<\/coupon-section>/g;
        var leagueLinksMatches = pageHtml.match(exp_text_all);
        var cmarkets = 0;

        let reset = await mysqlfunctions.promise_updateMarketsCount(cmarkets, table_markets_count, site);
        console.log(reset);

        if(leagueLinksMatches == null){
            return cmarkets;
        }
        for (let i = 0; i < leagueLinksMatches.length; i++) {
            const html = leagueLinksMatches[i];
            var expc = /class="title ellipsis-text">(.*?)<\/span/g;
            var nameChampionship = functions.getDataInHtmlCode(String(html).match(expc)[0]);

            var idChampionship = await mysqlfunctions.promise_db_insert_Championship(nameChampionship, gsport, table_championship);
           

            var exp_text = /<ui-event-line(.*?)<\/ui-event-line>/g;
            var text = html.match(exp_text);
            // console.info(text.length);

            for (let index = 0; index < text.length; index++) {
                const element = text[index];               
.... 
  

带递归回调的简单解决方案

然而,在我们开始之前,您可以尝试 运行 函数本身而不是 while,后者将在没有任何适当控制的情况下永远循环。

const readLoop = async() => {
  const html = await page.content();
  cant = await readOdds(html);
  return readLoop() // run the loop again
}

// invoke it for infinite callbacks without any delays at all
await readLoop();

只要您的 readOdds 函数 returns,相同的块将连续运行,没有任何延迟。您不必使用 page.waitForwhile.

防止内存泄露

对于在一段时间内重生的高级情况,bull and process manager like PM2 之类的队列开始发挥作用。但是,队列将使您的 without refresh the page? 部分问题无效。

不过你绝对应该使用 pm2。

用法如下,

npm i -g pm2
pm2 start index.js --name=myawesomeapp // or your app file

有用的论据很少,

  • --max-memory-restart 100M, 可以限制内存使用到100M并自行重启
  • --max-restarts 50, 错误(或内存泄漏)重启50次就会停止

您可以使用 pm2 logs myawesomeapp 查看日志,因为您在上面设置了名称。