Covid-19 cases update using Cheerio Library
Last Updated :
15 Mar, 2023
In this article we are going to learn about that how can we get the common information from the covid website i.e Total Cases, Recovered, and Deaths using the concept of scraping with help of JavaScript Library.
Library Requirements and installation: There are two libraries that are required to scrap(or get the required information from the website) the covid-19 website:
Request Library: This Request library will help us to get the HTML of the website by sending the HTTP request to that website. Because of this library, our manual tasks reduce.
Installation:
npm install request
Syntax:
request(url of website, function to get the response)
Note: The second parameter which is the function indicates that you can get the HTML, body, head, etc as a result by sending the request to a website.
Cheerio Library: This Cheerio library is used to wrap by obtaining the required data either in form of array type or individual data from the HTML that we had got by using the request library.
Installation:
npm install cheerio
Syntax:
cheerio.load(response on request)
Note: Load the HTML or any code that you had got as a response and then get the required data by passing the specific className or idName
Example: Let’s see the implementation to obtain the required data from the covid-19 website as explained below:
Javascript
const request = require( "request" );
const cheerio = require( "cheerio" );
function cb(err, response, html) {
if (err) {
console.log(err);
}
else {
handlehtml(html);
}
}
function handlehtml(html) {
let seltools = cheerio.load(html);
let content = seltools( "#maincounter-wrap span" );
let obj = [ "Coronavirus Cases: " , "Deaths: " , "Recovered: " ];
for (let i = 0; i < content.length; i++) {
let data = seltools(content[i]).text();
console.log(obj[i] + data);
}
}
|
Step to run the application: Write the below step in the terminal to run the application.
node fileName.js
Output:
Output
Explanation: First we requested the covid-19 website to get the HTML of that by using the request library and then we loaded the HTML by using the cheerio library to obtain the required data from that HTML by using the class name of the element in which the data was stored and as a result, we got the total cases, recovered and deaths as an output as you see above.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...