在 Puppeteer 中截取具有特定名称的不同元素的屏幕截图

Take screenshots of different elements with specific names in Puppeteer

我正在尝试截取可能包含多个部分的着陆页中的每个部分。我能够在我注释掉的“Round1”中有效地做到这一点。

我的目标是学习如何编写 leaner/cleaner 代码,所以我又尝试了一次,“Round2”。

在本节中,它确实截取了屏幕截图。但是,它截取了文件名为 JSHandle@node.png 的第 3 部分的屏幕截图。当然,我做错了。

第 1 轮(完美运行)

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())
;