我如何使用htmlparser2解析html文件?

Sar*_*rya 5 node.js html-parser

我正在使用Node.js,我需要解析一个html文件。现在,我使用了htmlparser2,它在parser.write(“ String”)方法中解析字符串。我可以使用html解析器解析html文件吗?如果是,那怎么办?

感谢帮助?

小智 -6

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();
Run Code Online (Sandbox Code Playgroud)

https://github.com/fb55/htmlparser2

http://demos.forbeslindesay.co.uk/htmlparser2/