簡體   English   中英

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

[英]Take screenshots of different elements with specific names in Puppeteer

我正在嘗試截取登錄頁面中每個部分的屏幕截圖,該頁面可能包含多個部分。 我能夠在我注釋掉的“Round1”中有效地做到這一點。

我的目標是學習如何編寫更精簡/更簡潔的代碼,所以我又做了一次嘗試,“Round2”。

在本節中,它確實截取了屏幕截圖。 但是,它使用文件名JSHandle@node.png截取第 3 節的屏幕截圖。 當然,我做錯了。

Round1(完美運行)

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

第2輪

我創建了一個包含所有變量的數組並嘗試遍歷它們。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM