Getting Started with Web Scraping in JavaScript

Web scraping is one of the most interesting things in the coding world.

What is web scraping?

Why is it even exist?

Let’s find out the answers.

What is Web Scraping?

Web scraping is an automated task to extract data from websites.

There are many applications of web scraping. Extracting the prices of products and comparing them with different. Getting a daily quote from the web. Building your own search engine like Google, Yahoo, etc.., The list goes on.

You can do more than you think with web scraping. Once you get to know how to extract the data from websites, then you can do whatever you want with the data.

The program which extracts the data from websites is called a web scraper. You are going to learn to write web scrapers in JavaScript.

There are mainly two parts to web scraping.

  • Getting the data using request libraries and a headless browser.
  • Parsing the data to extract the exact information that we want from the data.

Without further ado let’s get started.

Project Setup

I assume you have Node installed, if not check out the.

We are going to use the packages node-fetch and cheerio for web scraping in JavaScript.  Let’s set up the project with the npm to work with a third-party package.

Let’s quickly see the steps to complete our setup.

  • Create a directory called web_scraping and navigate to it.
  • Run the command npm init to initialize the project.
  • Answer all the questions based on your preference.
  • Now, install the packages using the command
npm install node-fetch cheerio

Let’s see the glimpses of the installed packages.

node-fetch

The package node-fetch brings the window.fetch to the node js environment. It helps to make the HTTP requests and get the raw data.

cheerio

The packageis used to parse and extract the information that is necessary from the raw data.

Two packages node-fetch and cheerio are good enough for web scraping in JavaScript. We are not going to see every method that the packages are providing. We will see the flow of web scraping and the most useful methods in that flow.

You will learn web scraping by doing it. So, let’s get to the work.

Scraping Cricket World Cup List

Here in this section, we are going to do actual web scraping.

What are we extracting?

By the title of the section, I think you would easily guess it. Yeah, whatever you are thinking is correct. Let’s extract all cricket world cup winners and runner-ups till now.

  • Create a file called extract_cricket_world_cups_list.js in the project.
  • We will be using thepage to get the desired information.
  • First, get the raw data using the node-fetch package.
  • Below code gets the raw data of the above Wikipedia page.
const fetch = require('node-fetch');// function to get the raw dataconst getRawData = (URL) => { return fetch(URL) .then((response) => response.text()) .then((data) => { return data; });};// URL for dataconst URL = '';// start of the programconst getCricketWorldCupsList = async () => { const cricketWorldCupRawData = await getRawData(URL); console.log(cricketWorldCupRawData);};// invoking the main functiongetCricketWorldCupsList();

We got the raw data from the URL. Now, it’s time to extract the information that we need from the raw data. Let’s use the package cheerio to extract the data.

Extracting data that involves HTML tags with cheerio is a cakewalk. Before getting into the actual data, let’s see some sample data parsing using cheerio.

  • Parse the HTML data using cheerio.load the method.
const parsedSampleData = cheerio.load( `<div id='container'><p id='title'>I'm title</p></div>` );
  • We have parsed the above HTML code. How to extract the p tag content from it? It’s the same as the selectors in JavaScript DOM manipulation.

console.log(parsedSampleData('#title').text());

You can select the tags as you want. You can check out different methods from the.

  • Now, it’s time to extract the world cup list. To extract the information, we need to know the HTML tags that information lies on the page. Go to theand inspect the page to get HTML tags information.

Here is the complete code.

const fetch = require('node-fetch');const cheerio = require('cheerio');// function to get the raw dataconst getRawData = (URL) => { return fetch(URL) .then((response) => response.text()) .then((data) => { return data; });};// URL for dataconst URL = '';// start of the programconst getCricketWorldCupsList = async () => { const cricketWorldCupRawData = await getRawData(URL); // parsing the data const parsedCricketWorldCupData = cheerio.load(cricketWorldCupRawData); // extracting the table data const worldCupsDataTable = parsedCricketWorldCupData('table.wikitable')[0] .children[1].children; console.log('Year --- Winner --- Runner'); worldCupsDataTable.forEach((row) => { // extracting `td` tags if (row.name === 'tr') { let year = null, winner = null, runner = null; const columns = row.children.filter((column) => column.name === 'td'); // extracting year const yearColumn = columns[0]; if (yearColumn) { year = yearColumn.children[0]; if (year) { year = year.children[0].data; } } // extracting winner const winnerColumn = columns[3]; if (winnerColumn) { winner = winnerColumn.children[1]; if (winner) { winner = winner.children[0].data; } } // extracting runner const runnerColumn = columns[5]; if (runnerColumn) { runner = runnerColumn.children[1]; if (runner) { runner = runner.children[0].data; } } if (year && winner && runner) { console.log(`${year} --- ${winner} --- ${runner}`); } } });};// invoking the main functiongetCricketWorldCupsList();

And, here is the scraped data.

Year --- Winner --- Runner1975 --- West Indies --- Australia1979 --- West Indies --- England1983 --- India --- West Indies1987 --- Australia --- England1992 --- Pakistan --- England1996 --- Sri Lanka --- Australia1999 --- Australia --- Pakistan2003 --- Australia --- India2007 --- Australia --- Sri Lanka2011 --- India --- Sri Lanka2015 --- Australia --- New Zealand2019 --- England --- New Zealand

Cool 😎, is int’ it?

Scraping Template

Getting the raw data from the URL is common in every web scraping project. The only part that changes is extracting the data as per the requirement. You can try the below code as a template.

const fetch = require('node-fetch');const cheerio = require('cheerio');const fs = require('fs');// function to get the raw dataconst getRawData = (URL) => { return fetch(URL) .then((response) => response.text()) .then((data) => { return data; });};// URL for dataconst URL = '';// start of the programconst scrapeData = async () => { const rawData = await getRawData(URL); // parsing the data const parsedData = cheerio.load(rawData); console.log(parsedData); // write code to extract the data // here // ... // ...};// invoking the main functionscrapeData();

Conclusion

You have learned how to scrape a webpage. Now, it’s your turn to.

I would also suggest checking out popularto explore and.

Happy Coding 🙂