上一篇文章我们介绍了一个html/xml解析器——htmlparser,这篇文章我们介绍另外一个解析模块htmlparser2,后者是对前者的重构,同时对前者的API做了部分兼容。
用法简介
安装
const { Parser } = require('htmlparser2');const parser = new Parser(handler, options);parser.parseComplete('html/xml内容');
写法
const { Parser } = require('htmlparser2');const parser = new Parser(handler, options);parser.parseComplete('html/xml内容');
htmlparser2提供了一个解析器——Parser,初始化它至少需要一个handler,options是可选的。
handler是一个对象,在这个对象上可以设置很多的钩子函数,Parser解析时会在每个阶段运行对应的钩子函数。
以下是可以设置的所有的钩子函数,
onopentag( name, attributes)onopentagname( name)onattribute( name, value)ontext( text)onclosetag( name)onprocessinginstruction( name, data)oncomment( data)oncommentend()oncdatastart()oncdataend()onerror( error)onreset()on