javascript - 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?
解决方案
当你点击“/”时,它会做很多事情,包括以下内容:
- 它会打开创建一个新的临时 chrome 配置文件。
- 使用某些标志和选项启动 chrome。
- 创建一个新选项卡。
- 加载目标网址。
- 等待一些事件触发。
- 评估您的代码。
- 关闭浏览器。
- 发送您的数据。
基本上它按照它的指示做。创建新 chrome 标签的速度取决于您的计算机资源,导航到该网站取决于您的计算机和目标网站。如果它是动态网站,那么各种页面加载事件都会增加成本。还有你的 UI 的开销。
因此,完成所有这些步骤需要 3-4 秒。
推荐阅读
- assembly - 使用 rN 寄存器 (r8,r9,...) 的汇编比其他寄存器具有更大的代码大小
- c# - 如何为多个文件夹(或文件)选择器配置对话框?
- google-sheets - Google表格脚本>将一行添加到3张表格之一时,将新行复制到另一张表格
- javascript - 下载按钮和输入字段在 JavaScript 中单击按钮时没有响应
- android - 如何在 Kotlin 中按名称属性过滤对象列表中的对象列表
- angular - 无法读取未定义的属性“管道”-Angular 6
- maven - maven shade插件带来旧的依赖
- android - 为 TextView 添加背景
- python - 在 PhantomJS 中设置自定义标题(使用 Python 的 Selenium)
- jquery - 如何获得下一个按钮以循环浏览 jquery 中的选项卡?