【问题标题】:How i can use htmlparser2 to parse html files?我如何使用 htmlparser2 来解析 html 文件?
【发布时间】:2015-06-14 14:02:53
【问题描述】:

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

感谢您的帮助?

【问题讨论】:

  • 使用“fs”模块将文件作为字符串打开并传递给解析器。

标签: node.js html-parser


【解决方案1】:
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();

https://github.com/fb55/htmlparser2

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

【讨论】:

  • 原始问题询问如何将 html 文件提供给解析器(没有 GET 请求)。
猜你喜欢
  • 2017-04-20
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
相关资源
最近更新 更多