这里贴出htmlparser2网址
简介:
htmlparser2是一个快速和宽容的HTML/XML/RSS
解析器,解析器可以出来流,并且提供了一个回调接口。
安装:
npm install htmlparser2
用法:
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();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
输出结果:
--> Xyz
JS! Hooray!
--> var foo = '<<bar>>';
That's it?!
htmlparser2的文档
用法:
var Parser = new htmlparser.Parser(<obj> handler[, <obj> options]);
对于处理器,下面是可以用的键的名字,注意:只有函数才可以作为值,否则解析器会失败:
- onopentag( name, attributes)
- onopentagname( name)
- onattribute( name, value)
- ontext( text)
- onclosetag( name)
- onprocessinginstruction( name, data)
- oncomment( data)
- oncommentend()
- oncdatastart()
- oncdataend()
- onerror( error)
- onreset()
- onend()