So you’ve probably heard of Web Scraping and what you can do with it, and you’re probably here because you want some more info on it.
Web Scraping is basically the process of extracting data from a website, that’s it.
As a web developer, you may have wanted to generate a PDF file of a web page to share with your clients, use it in presentations, or add it as a new feature in your web app. No matter your reason, Puppeteer, Google’s Node API for headless Chrome and Chromium, makes the task quite simple for you. Nodejs Web Scraper. Docs; Blog; Nodejs Web Scraper A simplified web scraper for Nodejs. Recursive scraping. Scrape/crawl deeply nested server-side rendered websites. Data collection. Hook into various steps of the scraping/crawling tree and collect the data. File & image downloading. I have used kafkajs to expose the data read from a kafka topic to be exposed via a http endpoint for prometheus to scrape the data. But I am not able to expose the data from kafka topic. I have written a producer and consumer like this.
Today we’re going to look at how you can start scraping with Puppeteer for NodeJs
Featured on
This article was featured already on multiple pages such as:
Javascript Daily’s Twitter
NodeJs Weekly – Issue #279
Thank you to everyone! 🔥
Table of contents
Puppeteer is a library created for NodeJs which basically gives you the ability to control everything on the Chrome or Chromium browser, with NodeJs.
You can do things like a normal browser would do and a normal human would, for example:
and many many more things
Puppeteer is created by the folks from Google and also maintained by them and even though’ the project is still pretty new to the market, it has skyrocketed over all the other competitors ( NightmareJs, Casper..etc ) with over 40 000 stars on github.
The first thing that you need to make sure is to have NodeJs installed in your PC or Mac.
After that you can initiate your first project on a new and empty folder with npm.
You can simply do this with the Terminal by going to the newly created folder and then running the following command:
Now you can input all the project details and you also can just hit Enter
After the setup you should now have a package.json
. file with content that looks similar to this:
Now we can start the installation of the needed Packages
Here’s what we’re going to need
So we are going to use npm install
While this is installing I’m going to take the time and explain to you What is Puppeteer
Puppeteer is an API that lets you manage the Chromium Browser with code written in NodeJs.
And the cool part about this is that Web Scraping with Puppeteer is very easy and beginner friendly.
Even beginners of Javascript can start to web scrape the web with Puppeteer because of it’s simplicity and because it is straight forward.
Now that we’re done with the boring stuff, let’s actually create an example just so that we can confirm that it’s working and see it in action.
Here is what we are going to build so that you get used to Puppeteer and understand how it works.
Lets create a simple web scraper for IMDB with Puppeteer
And here is what we need to do
Seems pretty easy, right?
I’m just going to give you a quick snippet of code and then we’re going to talk about it just a bit.
I am using the Google DevTools to check the html content and the classes so that I can generate a query selector for the Title, Rating and RatingCount
Learning the Selectors and how they work is very useful for this if you want to build custom selectors for different parts of the website that you want to scrape.
Here’s what I’ve built.
You can test out exactly this code and after running it you should see something like this
And of course, you can edit the code and improve it to go and scrape more details.
This was just for demonstration purposes so that you can see how powerful Web Scraping with Puppeteer is.
This code was written by me and tested in 15 minutesmaximum and I’m just trying to emphasize how easy and fast you can do certain things with Puppeteer.
There are multiple ways of running the code and I am going to show you 2 ways of doing that.
You can use the terminal to run it like you’ve probably heard of and you can do that with a simple command just like this:
And of course, you need to make sure you are in the right project directory with your terminal before actually running the code.
And instead of index.js, you can specify whatever file you want to run / execute.
And also you can run it directly with an editor that has the option to do so. In my case, I am using both VSCode and phpStorm
You can run it very easily with VSCode by clicking the Debugger tab and then just running it, simple and nice.
And of course, you can change the actual movie that you want to scrape by easily editing this part of the code:
Where you can input your actual movie id that you get from any IMDB Movie Urls that look like:
Where the actual movie id is this tt6763664.
Before I’m going to end this short tutorial, I want to give you the best snippets of code that you can use when building scrapers with Puppeteer.
Go ahead and replace the line where you initialize the browser, with this:
What is this going to do?
This is basically going to tell the Chromium browser to NOT use the headless mode, meaning it will show up on your screen and do all the commands you tell it to so that you can see it visually.
Why is this powerful?
Because of the simple fact that you can see and pause with a debugger on any point of the execution and check out what is exactly happening with your code.
This is very powerful when building it for the first time and when checking for errors.
You should not use this mode in a production build, use it for development only.
This is the reason Puppeteer is so cool, it is a browser that renders each page just like you would when you access it via your browser.
Why is this helpful?
With Puppeteer you can wait for certain elements on the page to be loaded up / rendered until you start scraping.
This is a massive advantage when you are dealing with
Puppeteer can handles everything that I had to deal with, regarding dynamic websites.
How?
Lets say you have a page that you are loading, and that page requests content via an ajax call.
You want to make sure that all that content is loaded fully before it starts to parse, because if the content that you are trying to parse is not there when the parsing happens, everything goes to waste.
You can easily handle this with the following statements
I feel like when you are starting out, debugging tips are the best because you try to do certain things and you don’t know for sure if they work and you just want to have the tools to debug your work and make it happen.
When you are doing scrapers with Puppeteer, you have the option to give a delay to the browser so that it slows down every action that you program it to do.
And this is basically going to slow it down by 250ms
This is also included to any kind of work you are doing with NodeJs so this tip will either blow your mind or you’ve known it already.
Usage of a debugger;
I personally use Visual Studio Code and PhpStorm with NodeJs plugin
If you don’t have a PhpStorm or WebStorm license, no worries, you can use VSCode
How to do you make use of the debugger?
You simply need to either put a Breakpoint or write debugger; j
And when you run it, it will then stop at exactly the line where you put the breakpoint or the debugger.
And how is this powerful?
If you still don’t know what I’m talking about, now after you are stuck in the debugger, you can access any variable available in that specific time, run code and inspect whatever it is you need.
If you still don’t use the debugger, you are missing out.
Before ending the actual code related content for this web scraping tutorial, I will give you a cool snippet to play around and also to make use of when needed.
Taking a screenshot of the current page opened with Puppeteer can be very useful for testing, debugging and not only.
Why is this useful?
It’s because, besides web scraping, you can use is for rendering dynamic pages and generate screenshots / previews for any page that you want to access.
You can easily do that with the following command
And you can place this wherever in the code where you want to take a screenshot and save it.
You can also check out the other parameters for the screenshot function from the actual Puppeteer .screenshot() function because there are a lot of other interesting parameters that you can give and make use of.
Connecting to a proxy can help in many cases where you either want to avoid getting banned on your servers or you want to test a website that is not accessible to your server’s country location or many other reasons.
It can be easily done with just one line of extra arguments passing when initiating the puppeteer browser.
If you have a username and password for your proxy server, then it would look something like this:
Where of course you would have to replace the USERNAME, PASSWORD and the IP & PORT.
Navigating to new pages with puppeteer and nodejs can be done very easily.
At the same time it can be a bit tricky sometimes.
Here’s what I mean by that:
When you either give a await page.goto() command or use a click function to click on a link with await page.click(), a new page is going to load.
The tricky part is to make sure the new page has been loaded properly and it actually is the page you are looking for.
At first, you can do something like this:
Which will basically click on a selector that is a link and starts the navigation to the next page.
With the waitForNavigation function you are basically waiting for the next page to load and to waitUntil there are no extra requests in the background for at least 500 ms.
This can work pretty well for most websites but there are cases, depending on the website that you are scraping, where this doesn’t work how you wanted it to because of constant requests in the background or because the website can be dynamically rendered.
In that case, the best option that I see ( and correct me or add to it in the comments ) is to wait for a specific selector that you know is going to exist in the page you want to access next.
Here is how you can do that
Where you would need to specify a selector that is only available on the next page you are expecting to be loaded.
And of course, it comes to this part where I need to tell you that Scraping is a gray area and not everyone accepts it.
Since you’re basically using someone else’s bandwidth and resources ( when you go to a page and scrape it ), you should be respectful and do it in a mannered way.
Don’t overdo it, know when to stop and what is exceeding the limit.
But how can I know that?
Think of what it actually means to go and scrape 10.000 users or images from someone else’s site and how will that impact the person running the site.
Think of what you would not like to have someone do to your website and don’t do that to others too.
If it seems shady, it probably is and you should probably not do it.
PS: Make sure to read the Terms of Service / Terms of Usage of the specific websites. Some have clear specific terms that don’t allow you to scrape and automate anything. ( Instagram for example )
Here is a list of resources that will definitely help you with nodejs scraping with puppeteer and not only.
These will set the base of your scraping knowledge and improve your existing one.
Hopefully you will give this a try and test for yourself the code, Puppeteer is very powerful and you can do a lot with it and fast also.
Also if you want to learn more and go much more in-depth with the downloading of files, I have a great course with more hours of good content on web scraping with nodejs.
As a web developer, you may have wanted to generate a PDF file of a web page to share with your clients, use it in presentations, or add it as a new feature in your web app. No matter your reason, Puppeteer, Google’s Node API for headless Chrome and Chromium, makes the task quite simple for you.
In this tutorial, we will see how to convert web pages into PDF with Puppeteer and Node.js. Let’s start the work with a quick introduction to what Puppeteer is.
In Google’s own words, Puppeteer is, “A Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol”.
If you are unfamiliar with the term headless browsers, it’s simply a browser without a GUI. In that sense, a headless browser is simply just another browser that understands how to render HTML web pages and process JavaScript. Due to the lack of a GUI, the interactions with a headless browser take place over a command line.
Even though Puppeteer is mainly a headless browser, you can configure and use it as non-headless Chrome or Chromium.
Puppeteer’s powerful browser-capabilities make it a perfect candidate for web app testing and web scraping.
To name a few use cases where Puppeteer provides the perfect functionalities for web developers,
You can use Puppeteer on the backend and frontend to generate PDFs. In this tutorial, we are using a Node backend for the task.
Initialize NPM and set up the usual Express server to get started with the tutorial.
Make sure to install the Puppeteer NPM package with the following command before you start.
Now we get to the exciting part of the tutorial. With Puppeteer, we only need a few lines of code to convert web pages into PDF.
First, create a browser instance using Puppeteer’s launch
function.
Then, we create a new page instance and visit the given page URL using Puppeteer.
We have set the waitUntil
option to networkidle0
. When we use networkidle0
option, Puppeteer waits until there are no new network connections within the last 500 ms. It is a way to determine whether the site has finished loading. It’s not exact, and Puppeteer offers other options, but it is one of the most reliables for most cases.
Finally, we create the PDF from the crawled page content and save it to our device.
The print to PDF function is quite complicated and allows for a lot of customization, which is fantastic. Here are some of the options we used:
When the PDF creation is over, close the browser connection with browser.close()
.
With the knowledge we gather so far, we can now create a new endpoint that will receive a URL as a query string, and then it will stream back to the client the generated PDF.
Here is the code:
If you start the server and visit the /pdf
route, with a target
query param containing the URL we want to convert. The server will serve the generated PDF directly without ever storing it on disk.
URL example: http://localhost:3000/pdf?target=https://google.com
Which will generate the following PDF as it looks on the image:
That’s it! You have completed the conversion of a web page to PDF. Wasn’t that easy?
As mentioned, Puppeteer offers many customization options, so make sure you play around with the opportunities to get different results.
Next, we can change the viewport size to capture websites under different resolutions.
In the previously created PDF, we didn’t specify the viewport size for the web page Puppeteer is visiting, instead used the default viewport size, 800×600px.
However, we can precisely set the page’s viewport size before crawling the page.
In today’s tutorial, we used Puppeteer, a Node API for headless Chrome, to generate a PDF of a given web page. Since you are now familiar with the basics of Puppeteer, you can use this knowledge in the future to create PDFs or even for other purposes like web scraping and UI testing.
Thanks for reading!