Skip to content

Instantly share code, notes, and snippets.

@robertkraig
Last active January 30, 2018 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertkraig/827b664fce142262b5d1abf3e83cd4d4 to your computer and use it in GitHub Desktop.
Save robertkraig/827b664fce142262b5d1abf3e83cd4d4 to your computer and use it in GitHub Desktop.
screenshot css element using puppeteer

node screenshot.js --fetchUrl=http://localhost/urlhere --cssSelector=.submission-result --writeToFile=./cache/filename.png

{
"private": true,
"scripts": {},
"dependencies": {
"axios": "^0.17",
"jquery": "^3.2",
"lodash": "^4.17.4",
"puppeteer": "^1.0.0",
"command-line-args": "^5.0.1",
"command-line-usage": "^4.1.0"
}
}
const puppeteer = require('puppeteer');
const CommandLineArgs = require('command-line-args');
const CommandLineUsage = require('command-line-usage');
const usage = CommandLineUsage([
{
header: 'Options',
optionList: [
{
name: 'fetchUrl',
description: 'http url path'
},
{
name: 'cssSelector',
description: 'markup-path'
},
{
name: 'writeToFile',
description: 'markup-path'
},
{
name: 'help',
description: 'Print this usage guide.'
}
]
}
]);
let options = null;
try{
options = CommandLineArgs([
{ name: 'fetchUrl', type: String },
{ name: 'cssSelector', type: String },
{ name: 'writeToFile', type: String },
{ name: 'help', type: String},
]);
}
catch(e)
{
console.log('Invalid field', e.message);
console.info(usage);
return;
}
if('help' in options)
{
console.info(usage);
return;
}
for(let field of ['fetchUrl', 'cssSelector', 'writeToFile'])
{
if(false === (field in options))
{
console.info(usage);
return 1;
}
}
(async () => {
const browser = await puppeteer.launch({args: ['--no-sandbox']});
const page = await browser.newPage();
await page.setViewport({width: 1920, height: 1080});
await page.goto(options['fetchUrl']);
await page.waitFor(1000);
try
{
let item = await page.$(options['cssSelector']);
item.screenshot({
path:options['writeToFile']
})
.then(res=>{
console.log({
path:options['writeToFile']
});
browser.close();
})
.catch(err=>{
console.error(err);
browser.close();
});
}catch(e){
console.log(e);
browser.close();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment