首页 > 解决方案 > Puppeteer takes too many seconds to load the data

问题描述

I have the following:

const puppeteer = require('puppeteer');
var express = require('express');
var app  = express();
var port = process.env.PORT || 3001;

app.listen(port);

app.get('/', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    (async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(`url`);

        const data = await page.evaluate(() => {
            const imgs = Array.from(document.querySelectorAll('.dp-gallery__list-item img'));
            return imgs.map(td => {
                var txt = td.src;
                return txt;
            });
        });

        res.send({ data });
        await browser.close();
    })();
});

the content that I need .dp-gallery__list-item img is loaded dynamically by js (I have tested it by disabling js) hence the use of puppeteer.

The issue I am facing is that every time I hit '/' it takes a good 3/4 seconds to receive the response in the ui:

const About = ({data}) => (
  <div>
    <Header />
    {data &&
        data.map(((img, i) => <img key={`${i} '-' ${img}`} src={img} />))
    }
    <p>Hello Next.js</p>
  </div>
);

About.getInitialProps = async ({query: {id}}) => {
    const res = await fetch('http://localhost:3001/');
    const data = await res.json();
    console.log('id: ', id);
    return data;
}

export default About;

Is it because the content I am looking for is loaded dynamically or am I missing something the the Puppeteer configuration?

标签: javascriptpuppeteer

解决方案


当你点击“/”时,它会做很多事情,包括以下内容:

  • 它会打开创建一个新的临时 chrome 配置文件。
  • 使用某些标志和选项启动 chrome。
  • 创建一个新选项卡。
  • 加载目标网址。
  • 等待一些事件触发。
  • 评估您的代码。
  • 关闭浏览器。
  • 发送您的数据。

基本上它按照它的指示做。创建新 chrome 标签的速度取决于您的计算机资源,导航到该网站取决于您的计算机和目标网站。如果它是动态网站,那么各种页面加载事件都会增加成本。还有你的 UI 的开销。

因此,完成所有这些步骤需要 3-4 秒。


推荐阅读