Take website screenshot on AJAX loading page using Puppeteer

0
4093
Google Puppeteer
Google Puppeteer

In previous post, I’ve introduced how to take screenshot for any web page using Puppeteer. However, it doesn’t work well for page implementing AJAX loading.

So what is the problem here? Well, it’s just normal browser behavior, since content is lazy-loaded, unless we scroll to the target, it won’t show up. To take a full page screenshot on this case, we need to do two extra steps:

– first is to scroll down to the bottom most of the page.
– and wait for the content to be loaded.

Finally, this is how we implemented to capture screenshot.


const puppeteer = require('puppeteer');

async function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.setViewport({ width: 1280, height: 800 })
    await page.goto('https://blog.petehouston.com/')
    await page.evaluate( () => window.scrollTo(0, document.body.scrollHeight))
    await timeout(3000)
    await page.screenshot({ path: 'blog.png', fullPage: true })
    await browser.close()
})()

Thanks to @jwillingham789 for timeout trick.