[英]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.