Home

Awesome

Node.js Web Crawler

npm npm GitHub issues David David Travis

Supercrawler is a Node.js web crawler. It is designed to be highly configurable and easy to use.

When Supercrawler successfully crawls a page (which could be an image, a text document or any other file), it will fire your custom content-type handlers. Define your own custom handlers to parse pages, save data and do anything else you need.

Features

How It Works

Crawling is controlled by the an instance of the Crawler object, which acts like a web client. It is responsible for coordinating with the priority queue, sending requests according to the concurrency and rate limits, checking the robots.txt rules and despatching content to the custom content handlers to be processed. Once started, it will automatically crawl pages until you ask it to stop.

The Priority Queue or UrlList keeps track of which URLs need to be crawled, and the order in which they are to be crawled. The Crawler will pass new URLs discovered by the content handlers to the priority queue. When the crawler is ready to crawl the next page, it will call the getNextUrl method. This method will work out which URL should be crawled next, based on implementation-specific rules. Any retry logic is handled by the queue.

The Content Handlers are functions which take content buffers and do some further processing with them. You will almost certainly want to create your own content handlers to analyze pages or store data, for example. The content handlers tell the Crawler about new URLs that should be crawled in the future. Supercrawler provides content handlers to parse links from HTML pages, analyze robots.txt files for Sitemap: directives and parse sitemap files for URLs.

Get Started

First, install Supercrawler.

npm install supercrawler --save

Second, create an instance of Crawler.

var supercrawler = require("supercrawler");

// 1. Create a new instance of the Crawler object, providing configuration
// details. Note that configuration cannot be changed after the object is
// created.
var crawler = new supercrawler.Crawler({
  // By default, Supercrawler uses a simple FIFO queue, which doesn't support
  // retries or memory of crawl state. For any non-trivial crawl, you should
  // create a database. Provide your database config to the constructor of
  // DbUrlList.
  urlList: new supercrawler.DbUrlList({
    db: {
      database: "crawler",
      username: "root",
      password: secrets.db.password,
      sequelizeOpts: {
        dialect: "mysql",
        host: "localhost"
      }
    }
  }),
  // Tme (ms) between requests
  interval: 1000,
  // Maximum number of requests at any one time.
  concurrentRequestsLimit: 5,
  // Time (ms) to cache the results of robots.txt queries.
  robotsCacheTime: 3600000,
  // Query string to use during the crawl.
  userAgent: "Mozilla/5.0 (compatible; supercrawler/1.0; +https://github.com/brendonboshell/supercrawler)",
  // Custom options to be passed to request.
  request: {
    headers: {
      'x-custom-header': 'example'
    }
  }
});

Third, add some content handlers.

// Get "Sitemaps:" directives from robots.txt
crawler.addHandler(supercrawler.handlers.robotsParser());

// Crawl sitemap files and extract their URLs.
crawler.addHandler(supercrawler.handlers.sitemapsParser());

// Pick up <a href> links from HTML documents
crawler.addHandler("text/html", supercrawler.handlers.htmlLinkParser({
  // Restrict discovered links to the following hostnames.
  hostnames: ["example.com"]
}));

// Match an array of content-type
crawler.addHandler(["text/plain", "text/html"], myCustomHandler);

// Custom content handler for HTML pages.
crawler.addHandler("text/html", function (context) {
  var sizeKb = Buffer.byteLength(context.body) / 1024;
  logger.info("Processed", context.url, "Size=", sizeKb, "KB");
});

Fourth, add a URL to the queue and start the crawl.

crawler.getUrlList()
  .insertIfNotExists(new supercrawler.Url("http://example.com/"))
  .then(function () {
    return crawler.start();
  });

That's it! Supercrawler will handle the crawling for you. You only have to define your custom behaviour in the content handlers.

Crawler

Each Crawler instance represents a web crawler. You can configure your crawler with the following options:

OptionDescription
urlListCustom instance of UrlList type queue. Defaults to FifoUrlList, which processes URLs in the order that they were added to the queue; once they are removed from the queue, they cannot be recrawled.
intervalNumber of milliseconds between requests. Defaults to 1000.
concurrentRequestsLimitMaximum number of concurrent requests. Defaults to 5.
robotsEnabledIndicates if the robots.txt is downloaded and checked. Defaults to true.
robotsCacheTimeNumber of milliseconds that robots.txt should be cached for. Defaults to 3600000 (1 hour).
robotsIgnoreServerErrorIndicates if 500 status code response for robots.txt should be ignored. Defaults to false.
userAgentUser agent to use for requests. Defaults to Mozilla/5.0 (compatible; supercrawler/1.0; +https://github.com/brendonboshell/supercrawler)
requestObject of options to be passed to request. Note that request does not support an asynchronous (and distributed) cookie jar.

Example usage:

var crawler = new supercrawler.Crawler({
  interval: 1000,
  concurrentRequestsLimit: 1
});

The following methods are available:

MethodDescription
getUrlListGet the UrlList type instance.
getIntervalGet the interval setting.
getConcurrentRequestsLimitGet the maximum number of concurrent requests.
getUserAgentGet the user agent.
startStart crawling.
stopStop crawling.
addHandler(handler)Add a handler for all content types.
addHandler(contentType, handler)Add a handler for a specific content type. If contentType is a string, then (for example) 'text' will match 'text/html', 'text/plain', etc. If contentType is an array of strings, the page content type must match exactly.

The Crawler object fires the following events:

EventDescription
crawlurl(url)Fires when crawling starts with a new URL.
crawledurl(url, errorCode, statusCode)Fires when crawling of a URL is complete. errorCode is null if no error occurred. statusCode is set if and only if the request was successful.
urllistemptyFires when the URL list is (intermittently) empty.
urllistcompleteFires when the URL list is permanently empty, barring URLs added by external sources. This only makes sense when running Supercrawler in non-distributed fashion.

DbUrlList

DbUrlList is a queue backed with a database, such as MySQL, Postgres or SQLite. You can use any database engine supported by Sequelize.

If a request fails, this queue will ensure the request gets retried at some point in the future. The next request is schedule 1 hour into the future. After that, the period of delay doubles for each failure.

Options:

OptionDescription
opts.db.databaseDatabase name.
opts.db.usernameDatabase username.
opts.db.passwordDatabase password.
opts.db.sequelizeOptsOptions to pass to sequelize.
opts.db.tableTable name to store URL queue. Default = 'url'
opts.recrawlInMsNumber of milliseconds to recrawl a URL. Default = 31536000000 (1 year)

Example usage:

new supercrawler.DbUrlList({
  db: {
    database: "crawler",
    username: "root",
    password: "password",
    sequelizeOpts: {
      dialect: "mysql",
      host: "localhost"
    }
  }
})

The following methods are available:

MethodDescription
insertIfNotExists(url)Insert a Url object.
upsert(url)Upsert Url object.
getNextUrl()Get the next Url to be crawled.

RedisUrlList

RedisUrlList is a queue backed with Redis.

If a request fails, this queue will ensure the request gets retried at some point in the future. The next request is schedule 1 hour into the future. After that, the period of delay doubles for each failure.

It also balances requests between different hostnames. So, for example, if you crawl a sitemap file with 10,000 URLs, the next 10,000 URLs will not be stuck in the same host.

Options:

OptionDescription
opts.redisOptions passed to ioredis.
opts.delayHalfLifeMsHostname delay factor half-life. Requests are delayed by an amount of time proportional to the number of pages crawled for a hostname, but this factor exponentially decays over time. Default = 3600000 (1 hour).
opts.expiryTimeMsAmount of time before recrawling a successful URL. Default = 2592000000 (30 days).
opts.initialRetryTimeMsAmount of time to wait before first retry after a failed URL. Default = 3600000 (1 hour)

Example usage:

new supercrawler.RedisUrlList({
  redis: {
    host: "127.0.0.1"
  }
})

The following methods are available:

MethodDescription
insertIfNotExists(url)Insert a Url object.
upsert(url)Upsert Url object.
getNextUrl()Get the next Url to be crawled.

FifoUrlList

The FifoUrlList is the default URL queue powering the crawler. You can add URLs to the queue, and they will be crawled in the same order (FIFO).

Note that, with this queue, URLs are only crawled once, even if the request fails. If you need retry functionality, you must use DbUrlList.

The following methods are available:

MethodDescription
insertIfNotExists(url)Insert a Url object.
upsert(url)Upsert Url object.
getNextUrl()Get the next Url to be crawled.

Url

A Url represents a URL to be crawled, or a URL that has already been crawled. It is uniquely identified by an absolute-path URL, but also contains information about errors and status codes.

OptionDescription
urlAbsolute-path string url
statusCodeHTTP status code or null.
errorCodeString error code or null.

Example usage:

var url = new supercrawler.Url({
  url: "https://example.com"
});

You can also call it just a string URL:

var url = new supercrawler.Url("https://example.com");

The following methods are available:

MethodDescription
getUniqueIdGet the unique identifier for this object.
getUrlGet the absolute-path string URL.
getErrorCodeGet the error code, or null if it is empty.
getStatusCodeGet the status code, or null if it is empty.

handlers.htmlLinkParser

A function that returns a handler which parses a HTML page and identifies any links.

OptionDescription
hostnamesArray of hostnames that are allowed to be crawled.
urlFilter(url, pageUrl)Function that takes a URL and returns true if it should be included.

Example usage:

var hlp = supercrawler.handlers.htmlLinkParser({
  hostnames: ["example.com"]
});
var hlp = supercrawler.handlers.htmlLinkParser({
  urlFilter: function (url) {
    return url.indexOf("page1") === -1;
  }
});

handlers.robotsParser

A function that returns a handler which parses a robots.txt file. Robots.txt file are automatically crawled, and sent through the same content handler routines as any other file. This handler will look for any Sitemap: directives, and add those XML sitemaps to the crawl.

It will ignore any files that are not /robots.txt.

If you want to extract the URLs from those XML sitemaps, you will also need to add a sitemap parser.

OptionDescription
urlFilter(sitemapUrl, robotsTxtUrl)Function that takes a URL and returns true if it should be included.

Example usage:

var rp = supercrawler.handlers.robotsParser();
crawler.addHandler("text/plain", supercrawler.handlers.robotsParser());

handlers.sitemapsParser

A function that returns a handler which parses an XML sitemaps file. It will pick up any URLs matching sitemapindex > sitemap > loc, urlset > url > loc.

It will also handle a gzipped file, since that it part of the sitemaps specification.

OptionDescription
urlFilterFunction that takes a URL and returns true if it should be included.

Example usage:

var sp = supercrawler.handlers.sitemapsParser();
crawler.addHandler(supercrawler.handlers.sitemapsParser());

Changelog

1.7.0

1.6.0

1.5.0

1.4.0

1.3.3

1.3.1

1.3.0

1.2.0

1.1.0

1.0.0

0.16.1

0.16.0

0.15.1

0.15.0

0.14.0

### 0.13.1

0.13.0

0.12.1

0.12.0

0.11.0

0.10.4

0.10.3

0.10.2

0.10.1

0.10.0

0.9.1

0.9.0

0.8.0

0.7.0

0.6.1

0.6.0

0.5.0

0.4.0

0.3.3

### 0.3.2

0.3.1

0.3.0

0.2.3

0.2.2

0.2.1

0.2.0

0.1.0