githubEdit

htmlparser2

NPM versionarrow-up-right Downloadsarrow-up-right Build Statusarrow-up-right Coveragearrow-up-right

A forgiving HTML/XML/RSS parser. The parser can handle streams and provides a callback interface.

Installation

npm install htmlparser2

A live demo of htmlparser2 is available herearrow-up-right.

Usage

var htmlparser = require("htmlparser2");
var parser = new htmlparser.Parser({
	onopentag: function(name, attribs){
		if(name === "script" && attribs.type === "text/javascript"){
			console.log("JS! Hooray!");
		}
	},
	ontext: function(text){
		console.log("-->", text);
	},
	onclosetag: function(tagname){
		if(tagname === "script"){
			console.log("That's it?!");
		}
	}
}, {decodeEntities: true});
parser.write("Xyz <script type='text/javascript'>var foo = '<<bar>>';</ script>");
parser.end();

Output (simplified):

Documentation

Read more about the parser and its options in the wikiarrow-up-right.

Get a DOM

The DomHandler (known as DefaultHandler in the original htmlparser module) produces a DOM (document object model) that can be manipulated using the DomUtilsarrow-up-right helper.

The DomHandler, while still bundled with this module, was moved to its own modulearrow-up-right. Have a look at it for further information.

Parsing RSS/RDF/Atom Feeds

Note: While the provided feed handler works for most feeds, you might want to use danmactough/node-feedparserarrow-up-right, which is much better tested and actively maintained.

Performance

After having some artificial benchmarks for some time, @AndreasMadsen published his htmlparser-benchmarkarrow-up-right, which benchmarks HTML parses based on real-world websites.

At the time of writing, the latest versions of all supported parsers show the following performance characteristics on Travis CIarrow-up-right (please note that Travis doesn't guarantee equal conditions for all tests):

How does this module differ from node-htmlparserarrow-up-right?

This is a fork of the htmlparser module. The main difference is that this is intended to be used only with node (it runs on other platforms using browserifyarrow-up-right). htmlparser2 was rewritten multiple times and, while it maintains an API that's compatible with htmlparser in most cases, the projects don't share any code anymore.

The parser now provides a callback interface close to sax.jsarrow-up-right (originally targeted at readabilitySAXarrow-up-right). As a result, old handlers won't work anymore.

The DefaultHandler and the RssHandler were renamed to clarify their purpose (to DomHandler and FeedHandler). The old names are still available when requiring htmlparser2, your code should work as expected.

Last updated