【发布时间】:2019-12-13 16:41:32
【问题描述】:
我正在尝试使用 puppeteer 截取网页的屏幕截图,我想通过 逐个显示它们 使用以下类型的数据逐个截取每个元素:
p (visibility:hidden)
ol
li (visibility:hidden)
li (visibility:hidden)
这样的话,我把p改成可见,截图,进入ol,设置li为可见,截图,等等。
我几乎可以使用以下功能:
const browser = await puppeteer.launch({args: ['--window-size=1920,1080','--no-sandbox', '--disable-setuid-sandbox']});
const page = await browser.newPage();
await page.goto('http://mywebsite',{waitUntil: 'networkidle2'});
const div = await page.$("[id^=t1_]");
const bbox = await div.boundingBox();
let nbElem=await page.evaluate(() => {
return document.querySelector('[class$=-root]').childElementCount
});
for(let i=1;i<=nbElem;i++){
await page.evaluate((i) => {
let elem = document.querySelector('[class$=-root] > *:nth-child('+i+')')
if(elem.tagName==="P"){
elem.style.visibility = 'visible';
div.screenshot({path: "test"+i+"0.png",clip: {x: bbox.x,y:bbox.y,width: bbox.width,height: bbox.height}})
}else{
let j=0;
let children = elem.children;
for(let z of children){
z.style.visibility='visible';
div.screenshot({path: "test"+i+(j++)+".png",clip: {x: bbox.x,y:bbox.y,width: bbox.width,height: bbox.height}})
}
}
},i);
// await div.screenshot({path: "test"+i+(j++)+".png",clip: {x: bbox.x,y:bbox.y,width: Math.min(bbox.width, page.viewport().width),height: Math.min(bbox.height, page.viewport().height),}})
}
在 await page.evaluate 中,我无法调用 div.screenshot,出现以下错误:
(node:26413) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: div.screenshot is not a function
我确实尝试使用 await 调用它,但又遇到了另一个错误:
await div.screenshot({path: "test"+i+"0.png",clip: {x: bbox.x,y:bbox.y,width: bbox.width,height: bbox.height}})
^^^^^
SyntaxError: await is only valid in async function
虽然在 page.evaluate 之后,我可以,但在这种情况下,我错过了每个 li 的“揭幕”。
在那种情况下,我绝对不知道我在用 await 和 async 的东西做什么......
我不明白如何将匿名函数转换为异步函数以适应 page.evaluate。
我应该如何在 page.evaluate 中调用 div.screenshot ?
谢谢
【问题讨论】:
-
在评估函数中不能调用截图
-
这部分还是没看懂:
const div = await page.$("[id^=t1_]")
标签: javascript async-await puppeteer