Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save leodutra/d880580f86620915b28a3eadccb81527 to your computer and use it in GitHub Desktop.
Save leodutra/d880580f86620915b28a3eadccb81527 to your computer and use it in GitHub Desktop.
Capture DOM elements screenshot using Chrome headless
const puppeteer = require('puppeteer')
// Related Issues:
// 3118 - https://github.com/GoogleChrome/puppeteer/issues/3118#issuecomment-417754246
async function main() {
const browser = await puppeteer.launch({
args: ['--start-maximized'],
headless: false,
defaultViewport: null
})
const page = (await browser.pages())[0]
await page.goto('https://coinmarketcap.com/', { waitUntil: 'networkidle0' })
await screenshotDOMElements({
page,
selector: 'table.dataTable > tbody > tr:nth-child(-n+50)',
deleteSelector: '.banner-alert-fixed-bottom',
path: 'element-1.png',
sumHeight: true
}),
await screenshotDOMElements({
page,
selector: 'table.dataTable > tbody > tr:nth-child(n+50)',
deleteSelector: '.banner-alert-fixed-bottom',
path: 'element-2.png',
sumHeight: true
})
console.log('Done!')
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error)
process.exit(1)
})
async function screenshotDOMElements({
page,
padding = 0,
path = null,
selector,
deleteSelector,
sumWidth = false,
sumHeight = false
} = {}) {
await page.evaluate(
deleteSelector => deleteSelector && document.querySelectorAll(deleteSelector).forEach(x => x.remove()),
deleteSelector
)
if (!selector) {
throw Error('Please provide a selector.')
}
const rect = await page.evaluate((selector, sumWidth, sumHeight) => {
let minX = Infinity
let minY = Infinity
let maxWidth = 0
let maxHeight = 0
const elements = document.querySelectorAll(selector)
if (elements) {
for (const element of elements) {
const {x, y, width, height} = element.getBoundingClientRect()
minX = Math.min(minX, x)
minY = Math.min(minY, y)
maxWidth = sumWidth
? maxWidth + width
: Math.max(maxWidth, width)
maxHeight = sumHeight
? maxHeight + height
: Math.max(maxHeight, height)
}
return {
left: minX,
top: minY,
width: maxWidth,
height: maxHeight
}
}
return null
}, selector, sumWidth, sumHeight)
if (!rect) {
throw Error(`Could not find element that matches selector: ${selector}.`)
}
return page.screenshot({
path,
clip: {
x: rect.left - padding,
y: rect.top - padding,
width: rect.width + padding * 2,
height: rect.height + padding * 2
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment