What is htmlparser2?
The htmlparser2 npm package is a fast and forgiving HTML and XML parser. It can parse HTML or XML into a DOM-like structure, which can then be manipulated or serialized. It is stream-based, which means it can handle large documents in a memory-efficient manner.
What are htmlparser2's main functionalities?
Parsing HTML to DOM
This feature allows you to parse HTML and handle different parts of the document as they are parsed. The example code sets up event handlers for opening tags, text content, and closing tags, and then parses a simple HTML string.
const htmlparser2 = require('htmlparser2');
const parser = new htmlparser2.Parser({
onopentag(name, attributes) {
console.log(name, attributes);
},
ontext(text) {
console.log(text);
},
onclosetag(tagname) {
console.log(tagname);
}
}, { decodeEntities: true });
parser.write('<div class="test">Hello World</div>');
parser.end();
Streaming Interface
This feature allows you to parse HTML from a stream, such as a file or network response. The example code creates a readable stream from a file and pipes it to the htmlparser2 stream, which logs tag openings, text content, and tag closings.
const htmlparser2 = require('htmlparser2');
const fs = require('fs');
const parser = new htmlparser2.WritableStream({
onopentag(name) {
console.log('Opened tag:', name);
},
ontext(text) {
console.log('Text:', text);
},
onclosetag(name) {
console.log('Closed tag:', name);
}
});
fs.createReadStream('example.html').pipe(parser);
DOM Tree Manipulation
This feature allows you to manipulate the DOM tree after parsing. The example code parses an HTML string into a DOM tree, changes the class attribute of the first element, and then serializes the modified element back to an HTML string.
const htmlparser2 = require('htmlparser2');
const dom = htmlparser2.parseDocument('<div class="test">Hello World</div>');
const divElement = dom.children[0];
divElement.attribs.class = 'new-class';
const serialized = htmlparser2.DomUtils.getOuterHTML(divElement);
console.log(serialized);
Other packages similar to htmlparser2
cheerio
Cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It uses a parser similar to htmlparser2 but provides a jQuery-like API for manipulating the resulting data structure. It is generally easier to use if you are familiar with jQuery.
jsdom
jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js. It is heavier than htmlparser2 but provides a more complete simulation of a web browser's environment, including the ability to execute scripts in the context of the parsed document.
parse5
parse5 is an HTML parsing/serialization toolset for Node.js that adheres to the HTML5 specification. It is more standards-compliant than htmlparser2 but may be slower due to its focus on correctness over speed.
#htmlparser2
A forgiving HTML/XML/RSS parser written in JS for NodeJS. The parser can handle streams (chunked data) and supports custom handlers for writing custom DOMs/output.
##Installing
npm install htmlparser2
##Running Tests
node tests/00-runtests.js
This project is linked to Travis CI. The latest builds status is:
##How is this different from node-htmlparser?
This is a fork of the project above. The main difference is that this is just intended to be used with node. Besides, the code is much better structured, has less duplications and is remarkably faster than the original.
Besides, the parser now provides the interface of sax.js (originally intended for my readability port readabilitySAX). I also fixed a couple of bugs & included some pull requests for the original project (eg. RDF feed support).
The support for location data and verbose output was removed a couple of versions ago. It's still available in the verbose branch (if you really need it, for whatever reason that may be).
##Usage
var htmlparser = require("htmlparser");
var rawHtml = "Xyz <script language= javascript>var foo = '<<bar>>';< / script><!--<!-- Waah! -- -->";
var handler = new htmlparser.DefaultHandler(function (error, dom) {
if (error)
[...do something for errors...]
else
[...parsing done, do something...]
console.log(dom);
});
var parser = new htmlparser.Parser(handler);
parser.write(rawHtml);
parser.done();
Output:
[{
data: 'Xyz ',
type: 'text'
}, {
type: 'script',
name: 'script',
attribs: {
language: 'javascript'
},
children: [{
data: 'var foo = \'<bar>\';<',
type: 'text'
}]
}, {
data: '<!-- Waah! -- ',
type: 'comment'
}]
##Streaming To Parser
while (...) {
...
parser.write(chunk);
}
parser.done();
##Parsing RSS/RDF/Atom Feeds
new htmlparser.FeedHandler(function (error, feed) {
...
});
##Further reading