【发布时间】:2019-10-12 13:43:34
【问题描述】:
我想用 htmlparser2 模块为 Node.js 解析一些 html。我的任务是通过其 ID 找到一个精确的元素并提取其文本内容。
我已经阅读了documentation(非常有限)并且我知道如何使用onopentag 函数设置我的解析器,但它只能访问标签名称及其属性(我看不到文本)。 ontext 函数从给定的 html 字符串中提取所有文本节点,但忽略所有标记。
这是我的代码。
const htmlparser = require("htmlparser2");
const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';
const parser = new htmlparser.Parser({
onopentag: function(name, attribs){
if (attribs.id === "heading1"){
console.log(/*how to extract text so I can get "Some heading" here*/);
}
},
ontext: function(text){
console.log(text); // Some heading \n Foobar
}
});
parser.parseComplete(file);
我希望函数调用的输出是'Some heading'。我相信有一些明显的解决方案,但不知何故,我没有想到。
谢谢。
【问题讨论】:
-
您是否有理由要使用这个特定的库?你一定要吗?对于某些人来说,像 Cheerio 这样的东西更容易使用,因为它有一个类似 jQuery 的界面,你可以利用。
-
感谢您的提问。不,我不必使用这个特定的库,但它似乎很受欢迎且速度很快。关于 Cheerio,我不懂 jQuery,所以看起来对我不太友好。
-
我会为你写一些东西。我不认为解析器是解决这个问题的方法。
-
我为你添加了答案。您在上面使用的库更多地是关于检查事物的结构,并且它对查询的支持是我理解的第二类。不过,我为您留下了两个示例,以便您学习。
标签: javascript node.js parsing html-parsing