Hi, welcome back to another tutorial on puppeteer and Node js. We have been on a series of tutorials concerning this powerful library. If you are totally new here, I will recommend you check out our recent tutorials on this subject and equally feel the magic of Google puppeteer. Puppeteer is real an awesome API, very useful in many ways.
Today, we will discuss how to perform screen capture of a particular area on the screen. Just like anyone would want to use snipping tool app to capture a particular area on the screen. As we already know, Puppeteer is headless chrome. Therefore, it behaves the way every user in front of a browser would do. To capture a particular portion of the screen, you need to;
- Open a browser,
- Create new tab or page,
- Type in a web address or url,
- capture the particular section you wish to,
- and save in a directory.
- Finally, close the browser (perhaps)
Puppeteer makes this possible without the need to open a physical browser window. Isn’t it glorious!!?
In our last article, we saw to capture screenshots and save in a directory. The exercise today is similar in code but except for the fact that we will have to set screen coordinates where we would want to capture..
...
Puppeteer uses the asynchronous function along side with specific methods to accomplish the steps mentioned above.
The following code has comments beside which explains each line. You should note that running such script needs to use a working internet connection as it requires opening a URL or website.
server.js
const puppeteer = require('puppeteer');
(async () => {const browser = await puppeteer.launch() //lauch browserconst page = await browser.newPage() //new page ...similar to a tab// set the viewport so we know the dimensions of the screenawait page.setViewport({ width: 1280, height: 800 }) // page sizeawait page.goto('https://www.trycoder.com/'); //open a linkawait page.screenshot({ //capture screen at given coordinates (clip)path: './uploads/image.png',fullPage: false,clip: {x: 0,y: 300,width: 1000, // captured image sizeheight: 100}})await browser.close() //close browserconsole.log ('done');})()
Ensure you have the uploads folder in your project directory.
Notice the extension put after the image name.
Output
After running the script, if everything goes well, it’ll log “done” on the console and then you will find the image in your directory.
And that’s it guys, we got the expected output.
To know more about the puppeteer methods, check the API documentation at: https://developers.google.com/web/tools/puppeteer
Comments
Post a Comment
Please do not enter any spam link in the comment box.