node.js - 我如何使用 htmlparser2 来解析 html 文件?

标签 node.js html-parser

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

感谢帮助?

最佳答案

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/

关于node.js - 我如何使用 htmlparser2 来解析 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830286/

相关文章:

node.js - Q 在 .then 成功回调中拒绝 promise

node.js - Nodejs 使用 readline 时暂停

PHP DOMDocument ParentNode->replaceChild 导致 foreach 跳过下一项

java - 用于响应的 HTML 解析器 - Java

node.js - 防止 Express.js 4.x 向最终用户显示异常详细信息

javascript - 找不到名称 'console' 。这可能是什么原因?

java - JSoup 检查 <HTML>、<HEAD> 和 <BODY> 标签是否存在

android - 从 asynctask android 获取字符串

javascript - node.js - 访问系统命令的退出代码和标准错误

支持表单发布的 .NET HTML 解析器