Skip to content

Instantly share code, notes, and snippets.

@jrosell
Created October 27, 2020 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jrosell/f53c8160133de8a4ffa1a44ecb027d03 to your computer and use it in GitHub Desktop.
Save jrosell/f53c8160133de8a4ffa1a44ecb027d03 to your computer and use it in GitHub Desktop.
Fetch and render using an specific google chrome version. We'll use appropiate zenika/alpine-chrome docker image.
// puppeteer-fetch-and-render-docker.js
// Fetch and render using an specific google chrome version
// We'll use appropiate zenika/alpine-chrome docker image. More information: https://github.com/Zenika/alpine-chrome
// Run:
// $ docker run -it --mount src="$(pwd)",target=/myproject,type=bind zenika/alpine-chrome:76-with-puppeteer /bin/sh
// /usr/src/app# cp /myproject/puppeteer-fetch-and-render.js .
// /usr/src/app# node puppeteer-fetch-and-render.js
// /usr/src/app# cp screenshot.png /myproject
// /usr/src/app# exit
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: true,
executablePath: '/usr/bin/chromium-browser',
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
// Descriptors for other mobile devices: https://github.com/puppeteer/puppeteer/blob/main/src/common/DeviceDescriptors.ts
const mobile = {
name: 'Nexus 5X',
userAgent:
'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
viewport: {
width: 412,
height: 732,
deviceScaleFactor: 2.625,
isMobile: true,
hasTouch: true,
isLandscape: false,
}
};
// Comment the next line if you want to render with the desktop version
await page.emulate(mobile);
// Modify with the URL you want to render
await page.goto('https://rawgit.com/GoogleChromeLabs/puppeteer-examples/master/html/lazyload.html', {waitUntil: 'load'});
await autoScroll(page);
console.log(await page.browser().version());
console.log(await page.content());
await page.screenshot({path: 'screenshot.png', fullPage: true});
await browser.close();
async function autoScroll(page){
await page.evaluate(async () => {
await new Promise((resolve, reject) => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if(totalHeight >= scrollHeight){
clearInterval(timer);
resolve();
}
}, 100);
});
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment