Chih- Yu Lin

1584934039

Remote fetching HTML data and Parse It in Express for NodeJS

Have you ever wanted to fetch remote HTML data in a similar fashion to cURL or Wget using some backend web service and parse it?  If you said no, don’t worry, I said the exact thing until I was challenged to do so.  For the challenge, I chose to use Express as my framework and a few libraries to assist in the process of fetching and parsing.

I chose to use the HTTP and HTTPS libraries for fetching the data and the htmlparser2 for parsing the HTML data.  These are of course only a few of many alternatives to choose from for such a task.

Before starting, I’m going to assume you’ve already got Express installed an setup.

Let’s go ahead and create a new Express project on our desktop:

express ParseProject

Now the HTTP and HTTPS libraries should already ship with your NodeJS installation.  If for any reason, we get into a jam, you can always force install the libraries with the project as your current working directory and the following:

npm install http --save
npm install https --save

I wouldn’t recommend installing the above unless we know for sure they aren’t already available.

Next let’s install the htmlparser2 library for traversing through our HTML:

npm install htmlparser2 --save

By using the --save flag, it adds reference to these dependencies in our package.json file.

Open the project’s routes/index.js file because this is where we’re going to do all of our coding. Make the top of your file look something like the following:

var express = require('express');
var http = require("http");
var https = require("https");
var htmlparser = require("htmlparser2");
var router = express.Router();

We can now choose to either do all of our coding in the main / route, or create another route.  I’m going to create a new route called /fetch which will be for fetching HTML data:

router.get("/fetch", function(req, res, next) {

});

To make our code a bit more dynamic, we’re going to allow a URL to be passed in as a GET parameter instead of working with a static website:

if(req.query.url === undefined) {
    res.send({message: "url cannot be undefined"});
}
var urlPrefix = req.query.url.match(/.*?:\/\//g);
req.query.url = req.query.url.replace(/.*?:\/\//g, "");
var options = {
    hostname: req.query.url
};

if(urlPrefix !== undefined && urlPrefix !== null && urlPrefix[0] === "https://") {
    options.port = 443;
    https.get(options, function(result) {
        processResponse(result);
    }).on('error', function(e) {
        res.send({message: e.message});
    });
} else {
    options.port = 80;
    http.get(options, function(result) {
        processResponse(result);
    }).on('error', function(e) {
        res.send({message: e.message});
    });
}

So what is happening in the above code? We’re checking to see if a url was passed with the query parameters.  If it wasn’t then return an error.  If it was, then we are going to use a regular expression to extract the prefix of the URL and then remove it from the URL.  We do this because if the URL uses SSL, then we need to use HTTPS rather than HTTP.

The rest leads us to our next function:

var processResponse = function(result) {
    var data = "";
    result.on("data", function(chunk) {
        data += chunk;
    });
    var tags = [];
    var tagsCount = {};
    var tagsWithCount = [];
    result.on("end", function(chunk) {
        var parser = new htmlparser.Parser({
            onopentag: function(name, attribs) {
                if(tags.indexOf(name) === -1) {
                    tags.push(name);
                    tagsCount[name] = 1;
                } else {
                    tagsCount[name]++;
                }
            },
            onend: function() {
                for(var i = 0; i < tags.length; i++) {
                    tagsWithCount.push({name: tags[i], count: tagsCount[tags[i]]});
                }
            }
        }, {decodeEntities: true});
        parser.write(data);
        parser.end();
        res.send({website: req.query.url, port: options.port, data: data, tags: tagsWithCount});
    });
}

In the above function we are getting all the remote HTML data and then using the htmlparser2 to figure out what tag names exist and how many of each tag name exist.

We are then choosing to report all this information back.

Here is the code for the full routes/index.js file in case you’l like to see it all put together:

router.get("/fetch", function(req, res, next) {
    if(req.query) {
        if(req.query.url === undefined) {
            res.send({message: "url cannot be undefined"});
        }
        var urlPrefix = req.query.url.match(/.*?:\/\//g);
        req.query.url = req.query.url.replace(/.*?:\/\//g, "");
        var options = {
            hostname: req.query.url
        };

        if(urlPrefix !== undefined && urlPrefix !== null && urlPrefix[0] === "https://") {
            options.port = 443;
            https.get(options, function(result) {
                processResponse(result);
            }).on('error', function(e) {
                res.send({message: e.message});
            });
        } else {
            options.port = 80;
            http.get(options, function(result) {
                processResponse(result);
            }).on('error', function(e) {
                res.send({message: e.message});
            });
        }

        var processResponse = function(result) {
            var data = "";
            result.on("data", function(chunk) {
                data += chunk;
            });
            var tags = [];
            var tagsCount = {};
            var tagsWithCount = [];
            result.on("end", function(chunk) {
                var parser = new htmlparser.Parser({
                    onopentag: function(name, attribs) {
                        if(tags.indexOf(name) === -1) {
                            tags.push(name);
                            tagsCount[name] = 1;
                        } else {
                            tagsCount[name]++;
                        }
                    },
                    onend: function() {
                        for(var i = 0; i < tags.length; i++) {
                            tagsWithCount.push({name: tags[i], count: tagsCount[tags[i]]});
                        }
                    }
                }, {decodeEntities: true});
                parser.write(data);
                parser.end();
                res.send({website: req.query.url, port: options.port, data: data, tags: tagsWithCount});
            });
        }

    }
});

How about testing this thing out?  With the project as your current directory in the command prompt or terminal, run the following:

npm start

This will start your project on http://localhost:3000 for viewing.  From your web browser, hit http://localhost:3000/fetch?url=https://www.slack.com and see what happens.  With a little luck you should get all the HTML data and information about the tags.

Conclusion

If for some reason you wanted to get and parse HTML data with Express for NodeJS, you could make use of the HTTP, HTTPS, and htmlparser2 dependencies.  There are a lot of alternative libraries that can accomplish the same.  We then can create a custom route and return the data as JSON for an API-like response

#html #nodejs #node #Express #javascript

What is GEEK

Buddha Community

Remote fetching HTML data and Parse It in Express for NodeJS
Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

Gerhard  Brink

Gerhard Brink

1620629020

Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.

Introduction

As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).


This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management

Chih- Yu Lin

1584934039

Remote fetching HTML data and Parse It in Express for NodeJS

Have you ever wanted to fetch remote HTML data in a similar fashion to cURL or Wget using some backend web service and parse it?  If you said no, don’t worry, I said the exact thing until I was challenged to do so.  For the challenge, I chose to use Express as my framework and a few libraries to assist in the process of fetching and parsing.

I chose to use the HTTP and HTTPS libraries for fetching the data and the htmlparser2 for parsing the HTML data.  These are of course only a few of many alternatives to choose from for such a task.

Before starting, I’m going to assume you’ve already got Express installed an setup.

Let’s go ahead and create a new Express project on our desktop:

express ParseProject

Now the HTTP and HTTPS libraries should already ship with your NodeJS installation.  If for any reason, we get into a jam, you can always force install the libraries with the project as your current working directory and the following:

npm install http --save
npm install https --save

I wouldn’t recommend installing the above unless we know for sure they aren’t already available.

Next let’s install the htmlparser2 library for traversing through our HTML:

npm install htmlparser2 --save

By using the --save flag, it adds reference to these dependencies in our package.json file.

Open the project’s routes/index.js file because this is where we’re going to do all of our coding. Make the top of your file look something like the following:

var express = require('express');
var http = require("http");
var https = require("https");
var htmlparser = require("htmlparser2");
var router = express.Router();

We can now choose to either do all of our coding in the main / route, or create another route.  I’m going to create a new route called /fetch which will be for fetching HTML data:

router.get("/fetch", function(req, res, next) {

});

To make our code a bit more dynamic, we’re going to allow a URL to be passed in as a GET parameter instead of working with a static website:

if(req.query.url === undefined) {
    res.send({message: "url cannot be undefined"});
}
var urlPrefix = req.query.url.match(/.*?:\/\//g);
req.query.url = req.query.url.replace(/.*?:\/\//g, "");
var options = {
    hostname: req.query.url
};

if(urlPrefix !== undefined && urlPrefix !== null && urlPrefix[0] === "https://") {
    options.port = 443;
    https.get(options, function(result) {
        processResponse(result);
    }).on('error', function(e) {
        res.send({message: e.message});
    });
} else {
    options.port = 80;
    http.get(options, function(result) {
        processResponse(result);
    }).on('error', function(e) {
        res.send({message: e.message});
    });
}

So what is happening in the above code? We’re checking to see if a url was passed with the query parameters.  If it wasn’t then return an error.  If it was, then we are going to use a regular expression to extract the prefix of the URL and then remove it from the URL.  We do this because if the URL uses SSL, then we need to use HTTPS rather than HTTP.

The rest leads us to our next function:

var processResponse = function(result) {
    var data = "";
    result.on("data", function(chunk) {
        data += chunk;
    });
    var tags = [];
    var tagsCount = {};
    var tagsWithCount = [];
    result.on("end", function(chunk) {
        var parser = new htmlparser.Parser({
            onopentag: function(name, attribs) {
                if(tags.indexOf(name) === -1) {
                    tags.push(name);
                    tagsCount[name] = 1;
                } else {
                    tagsCount[name]++;
                }
            },
            onend: function() {
                for(var i = 0; i < tags.length; i++) {
                    tagsWithCount.push({name: tags[i], count: tagsCount[tags[i]]});
                }
            }
        }, {decodeEntities: true});
        parser.write(data);
        parser.end();
        res.send({website: req.query.url, port: options.port, data: data, tags: tagsWithCount});
    });
}

In the above function we are getting all the remote HTML data and then using the htmlparser2 to figure out what tag names exist and how many of each tag name exist.

We are then choosing to report all this information back.

Here is the code for the full routes/index.js file in case you’l like to see it all put together:

router.get("/fetch", function(req, res, next) {
    if(req.query) {
        if(req.query.url === undefined) {
            res.send({message: "url cannot be undefined"});
        }
        var urlPrefix = req.query.url.match(/.*?:\/\//g);
        req.query.url = req.query.url.replace(/.*?:\/\//g, "");
        var options = {
            hostname: req.query.url
        };

        if(urlPrefix !== undefined && urlPrefix !== null && urlPrefix[0] === "https://") {
            options.port = 443;
            https.get(options, function(result) {
                processResponse(result);
            }).on('error', function(e) {
                res.send({message: e.message});
            });
        } else {
            options.port = 80;
            http.get(options, function(result) {
                processResponse(result);
            }).on('error', function(e) {
                res.send({message: e.message});
            });
        }

        var processResponse = function(result) {
            var data = "";
            result.on("data", function(chunk) {
                data += chunk;
            });
            var tags = [];
            var tagsCount = {};
            var tagsWithCount = [];
            result.on("end", function(chunk) {
                var parser = new htmlparser.Parser({
                    onopentag: function(name, attribs) {
                        if(tags.indexOf(name) === -1) {
                            tags.push(name);
                            tagsCount[name] = 1;
                        } else {
                            tagsCount[name]++;
                        }
                    },
                    onend: function() {
                        for(var i = 0; i < tags.length; i++) {
                            tagsWithCount.push({name: tags[i], count: tagsCount[tags[i]]});
                        }
                    }
                }, {decodeEntities: true});
                parser.write(data);
                parser.end();
                res.send({website: req.query.url, port: options.port, data: data, tags: tagsWithCount});
            });
        }

    }
});

How about testing this thing out?  With the project as your current directory in the command prompt or terminal, run the following:

npm start

This will start your project on http://localhost:3000 for viewing.  From your web browser, hit http://localhost:3000/fetch?url=https://www.slack.com and see what happens.  With a little luck you should get all the HTML data and information about the tags.

Conclusion

If for some reason you wanted to get and parse HTML data with Express for NodeJS, you could make use of the HTTP, HTTPS, and htmlparser2 dependencies.  There are a lot of alternative libraries that can accomplish the same.  We then can create a custom route and return the data as JSON for an API-like response

#html #nodejs #node #Express #javascript

Cyrus  Kreiger

Cyrus Kreiger

1618039260

How Has COVID-19 Impacted Data Science?

The COVID-19 pandemic disrupted supply chains and brought economies around the world to a standstill. In turn, businesses need access to accurate, timely data more than ever before. As a result, the demand for data analytics is skyrocketing as businesses try to navigate an uncertain future. However, the sudden surge in demand comes with its own set of challenges.

Here is how the COVID-19 pandemic is affecting the data industry and how enterprises can prepare for the data challenges to come in 2021 and beyond.

#big data #data #data analysis #data security #data integration #etl #data warehouse #data breach #elt

Macey  Kling

Macey Kling

1597579680

Applications Of Data Science On 3D Imagery Data

CVDC 2020, the Computer Vision conference of the year, is scheduled for 13th and 14th of August to bring together the leading experts on Computer Vision from around the world. Organised by the Association of Data Scientists (ADaSCi), the premier global professional body of data science and machine learning professionals, it is a first-of-its-kind virtual conference on Computer Vision.

The second day of the conference started with quite an informative talk on the current pandemic situation. Speaking of talks, the second session “Application of Data Science Algorithms on 3D Imagery Data” was presented by Ramana M, who is the Principal Data Scientist in Analytics at Cyient Ltd.

Ramana talked about one of the most important assets of organisations, data and how the digital world is moving from using 2D data to 3D data for highly accurate information along with realistic user experiences.

The agenda of the talk included an introduction to 3D data, its applications and case studies, 3D data alignment, 3D data for object detection and two general case studies, which are-

  • Industrial metrology for quality assurance.
  • 3d object detection and its volumetric analysis.

This talk discussed the recent advances in 3D data processing, feature extraction methods, object type detection, object segmentation, and object measurements in different body cross-sections. It also covered the 3D imagery concepts, the various algorithms for faster data processing on the GPU environment, and the application of deep learning techniques for object detection and segmentation.

#developers corner #3d data #3d data alignment #applications of data science on 3d imagery data #computer vision #cvdc 2020 #deep learning techniques for 3d data #mesh data #point cloud data #uav data