[英]Take screenshots of different elements with specific names in Puppeteer
我正在嘗試截取登錄頁面中每個部分的屏幕截圖,該頁面可能包含多個部分。 我能夠在我注釋掉的“Round1”中有效地做到這一點。
我的目標是學習如何編寫更精簡/更簡潔的代碼,所以我又做了一次嘗試,“Round2”。
在本節中,它確實截取了屏幕截圖。 但是,它使用文件名JSHandle@node.png
截取第 3 節的屏幕截圖。 當然,我做錯了。
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.somelandingpage.com');
// const elOne = await page.$('.section-one');
// await elOne.screenshot({path: './public/SectionOne.png'})
// takes a screenshot SectionOne.png
// const elTwo = await page.$('.section-two')
// await elTwo.screenshot({path: './public/SectionTwo.png'})
// takes a screenshot SectionTwo.png
// const elThree = await page.$('.section-three')
// await elThree.screenshot({path: './public/SectionThree.png'})
// takes a screenshot SectionThree.png
我創建了一個包含所有變量的數組並嘗試遍歷它們。
const elOne = await page.$('.section-one');
const elTwo = await page.$('.section-two')
const elThree = await page.$('.section-three')
let lpElements = [elOne, elTwo, elThree];
for(var i=0; i<lpElements.length; i++){
await lpElements[i].screenshot({path: './public/'+lpElements[i] + '.png'})
}
await browser.close();
})();
這僅截取第三部分的屏幕截圖,但文件名錯誤( JSHandle@node.png
)。 控制台上沒有錯誤消息。 如何通過修改 Round2 代碼來重現 Round1?
您的數組僅包含正在調用.toString()
的 Puppeteer 元素句柄對象。
一個干凈的方法是使用一個對象數組,每個對象都有一個選擇器及其名稱。 然后,當您運行循環時,您可以訪問名稱和選擇器。
const puppeteer = require('puppeteer');
const content = `
<div class="section-one">foo</div>
<div class="section-two">bar</div>
<div class="section-three">baz</div>
`;
const elementsToScreenshot = [
{selector: '.section-one', name: 'SectionOne'},
{selector: '.section-two', name: 'SectionTwo'},
{selector: '.section-three', name: 'SectionThree'},
];
const getPath = name => `./public/${name}.png`;
let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.setContent(content);
for (const {selector, name} of elementsToScreenshot) {
const el = await page.$(selector);
await el.screenshot({path: getPath(name)});
}
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.