Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7573713
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T16:15:08+00:00 2026-05-30T16:15:08+00:00

This is a simple scraper written in JavaScript with Node.js, for scraping Wikipedia for

  • 0

This is a simple scraper written in JavaScript with Node.js, for scraping Wikipedia for periodic table element data. The dependencies are jsdom for DOM manipulation and chain-gang for queuing.

It works fine, most of the time (it doesn’t handle errors gracefully), and the code isn’t too bad, dare I say for a for attempt, but there is a serious fault with it – it leaks memory horribly, anywhere from 0.3% to 0.6% of the computer’s memory for each element, such that by the time it gets to lead it would be using somewhere close to 20%, which is plainly unacceptable.

I’ve tried working with profilers, but I have either not found them to be helpful or have difficulty interpreting the data. I suspect it has something to do with the way processElement gets passed around, but I have difficulty in rewriting the queue code into something more elegant.

var fs = require('fs'),
    path = require('path'),
    jsdom = require("jsdom"),
    parseUrl = require('url').parse,
    chainGang = require('chain-gang');

var chain = chainGang.create({
    workers: 1
});

var Settings = {
    periodicUrl: 'http://en.wikipedia.org/wiki/Template:Periodic_table',
    periodicSelector: '#bodyContent > table:first',
    pathPrefix: 'data/',
    ignoredProperties: ['Pronunciation']
};

function writeToFile(output) {
    var keys = 0;

    // Huge nests for finding the name of the element... yeah
    for(var i in output) {
        if(typeof output[i] === 'object' && output[i] !== null){
            for(var l in output[i]) {
                if(l.toLowerCase() === 'name') {
                    var name = output[i][l];
                }
            }

            keys += Object.keys(output[i]).length;
        }
    }

    console.log('Scraped ' + keys + ' properties for ' + name);
    console.log('Writing to ' + Settings.pathPrefix + name + '.json');
    fs.writeFile(Settings.pathPrefix + name + '.json', JSON.stringify(output));
}

// Generic create task function to create a task function that
// would be passed to the chain gang
function createTask (url, callback) {
    console.log('Task added - ' + url);

    return function(worker){
        console.log('Requesting: ' +url);

        jsdom.env(url, [
            'jquery.min.js' // Local copy of jQuery
        ], function(errors, window) {
            if(errors){
                console.log('Error! ' + errors)
                createTask(url, callback);
            } else {
                // Give me thy $
                var $ = window.$;

                // Cleanup - remove unneeded elements
                $.fn.cleanup = function() {
                    return this.each(function(){
                        $(this).find('sup.reference, .IPA').remove().end()
                            .find('a, b, i, small, span').replaceWith(function(){
                                return this.innerHTML;
                            }).end()
                            .find('br').replaceWith(' ');
                    });
                }

                callback($);
            }

            worker.finish();
        });
    }
}

function processElement ($){
    var infoBox = $('.infobox'),
        image = infoBox.find('tr:contains("Appearance") + tr img:first'),
        description = $('#toc').prevAll('p').cleanup(),
        headers = infoBox.find('tr:contains("properties")'),
        output = {
            Appearance: image.attr('src'),
            Description: $('.infobox + p').cleanup().html()
        };

    headers.each(function(){
        var that = this,
            title = this.textContent.trim(),
            rowspan = 0,
            rowspanHeading = '';

        output[title] = {};

        $(this).nextUntil('tr:has(th:only-child)').each(function(){
            var t = $(this).cleanup(),
                headingEle = t.children('th'),
                data = t.children('td').html().trim();

            if(headingEle.length) {
                var heading = headingEle.html().trim();
            }

            // Skip to next heading if current property is ignored
            if(~Settings.ignoredProperties.indexOf(heading)) {
                return true;
            }

            if (rowspan) {
                output[title][rowspanHeading][data.split(':')[0].trim()] = data.split(':')[1].trim();
                rowspan--;
            } else if (headingEle.attr('rowspan')){
                rowspan = headingEle.attr('rowspan') - 1;
                rowspanHeading = heading;

                output[title][heading] = {};
                output[title][heading][data.split(':')[0]] = data.split(':')[1];
            } else if (~heading.indexOf(',')){
                data = data.split(',');

                heading.split(',').forEach(function(v, i){
                    output[title][v.trim()] = data[i].trim();
                });
            } else {
                output[title][heading] = data;
            }
        });
    });

    writeToFile(output);
}

function fetchElements(elements) {
    elements.forEach(function(value){
        // Element URL used here as task id (second argument)
        chain.add(createTask(value, processElement), value);
    });
}

function processTable($){
    var elementArray = $(Settings.periodicSelector).find('td').map(function(){
        var t = $(this),
            atomicN = parseInt(t.text(), 10);

        if(atomicN && t.children('a').length) {
            var elementUrl = 'http://' + parseUrl(Settings.periodicUrl).host + t.children('a:first').attr('href');

            console.log(atomicN, t.children('a:first').attr('href').split('/').pop(), elementUrl);
            return elementUrl;
        }
    }).get();

    fetchElements(elementArray);
    fs.writeFile(Settings.pathPrefix + 'elements.json', JSON.stringify(elementArray));
}

// Get table - init
function getPeriodicList(){
    var elementsList = Settings.pathPrefix + 'elements.json';

    if(path.existsSync(elementsList)){
        var fileData = JSON.parse(fs.readFileSync(elementsList, 'utf8'));
        fetchElements(fileData);
    } else {
        chain.add(createTask(Settings.periodicUrl, processTable));
    }
}

getPeriodicList();
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T16:15:09+00:00Added an answer on May 30, 2026 at 4:15 pm

    For jQuery-like html processing with node i use now cheerio instead of jsdom. So far, i have not seen any memory leaks while scrapping and parsing over 10K pages for a couple of hours.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hoping this is possible with Simple Html Dom, I'm scraping a page that looks
This simple code is not producing any sound on a couple of machines that
This simple example fails to compile in VS2K8: io_service io2; shared_ptr<asio::deadline_timer> dt(make_shared<asio::deadline_timer>(io2, posix_time::seconds(20))); As
This simple regex matching returns a string instead of an object on every browser
This simple Python method I put together just checks to see if Tomcat is
Consider this simple XML document. The serialized XML shown here is the result of
Consider this simple markup: <body> <div style=border: 2px solid navy; position:absolute; width:100%; height:100%> </div>
Imagine this simple form <form action=<?php echo $_SERVER['REQUEST_URI']; ?> method=post> <fieldset> <legend>Contact Me</legend> <label
Consider this simple example (which displays in red): echo -e \033[31mHello World\033[0m It displays
take this simple code: class A{ public: virtual void foo() = 0; void x(){

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.