[英]How to return data from page.evaluate() in Puppeteer, when there is Promise.all() inside browser in JavaScript
我想找到页面中所有图像的平均颜色。 我正在使用 Puppeteer 启动 chromium,然后在浏览器中运行 javascript。
问题是我正在使用 Promies.all 异步计算浏览器内的所有 colors 。
我想将计算得到的图像 colors 返回到 page.evaluate。 我怎样才能做到这一点? 可能吗?
以下代码不起作用,因为 imgcolors 显然没有定义,它在 Promise.all 回调中返回。
const returned = await page.evaluate(async () => {
const fac = new FastAverageColor();
const imgs = Array.from(document.querySelectorAll('img'));
const imgpromises = imgs.map(img => fac.getColorAsync(img.src));
Promise.all(imgpromises).then(imgcolors => { return imgcolors;});
return {
document:{
height: document.body.scrollHeight,
width:document.body.scrollWidth
},
imgcolors:imgcolors
};
});
我试过以下:
Promise.all(imgpromises).then(imgcolors => {
return {
elements:elements,
document:{
height: document.body.scrollHeight,
width:document.body.scrollWidth
},
imgcolors:imgcolors
};
});
现在我不会将数据返回到 page.evaluate puppeteer function。 所以返回的 const 是未定义的。
怎么做? 先感谢您!
在page.evaluate
function 中,可以返回一个 promise,它将解析为一个值。 在这种情况下, Promise.all
返回一个 promise,您可以链接它以返回您想要的值。 它看起来像这样:
const returned = await page.evaluate(() => {
const fac = new FastAverageColor();
const imgs = Array.from(document.querySelectorAll('img'));
const imgpromises = imgs.map(img => fac.getColorAsync(img.src));
return Promise.all(imgpromises).then(imgcolors => {
return {
document:{
height: document.body.scrollHeight,
width: document.body.scrollWidth
},
imgcolors: imgcolors
};
});
});
或者,由于您使用的是async
函数,您可以只使用await
运算符来等待解析值:
const returned = await page.evaluate(async () => {
const fac = new FastAverageColor();
const imgs = Array.from(document.querySelectorAll('img'));
const imgpromises = imgs.map(img => fac.getColorAsync(img.src));
const imgcolors = await Promise.all(imgpromises);
return {
document:{
height: document.body.scrollHeight,
width: document.body.scrollWidth
},
imgcolors: imgcolors
};
});
注意page.evaluate
只能返回可序列化的值,即可以是JSON.stringify
的东西。 看起来imgcolors
应该是可序列化的,但在其他情况下,您可能需要将值转换为可序列化的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.