javascript - 在 Node.js 中使用 htmlparser2 选择 html Node 的文本内容

标签 javascript node.js parsing html-parsing

我想用 htmlparser2 解析一些 html Node.js 的模块。我的任务是通过 ID 找到精确的元素并提取其文本内容。

我已阅读 documentation (相当有限),我知道如何使用 onopentag 函数设置我的解析器,但它只提供对标签名称及其属性的访问(我看不到文本)。 ontext 函数从给定的 html 字符串中提取所有文本 Node ,但忽略所有标记。

这是我的代码。

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 header'。我相信有一些明显的解决方案,但不知何故它忽略了我的想法。

谢谢。

最佳答案

您可以使用您询问的库来执行此操作:

const htmlparser = require('htmlparser2');
const domUtils = require('domutils');

const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';

var handler = new htmlparser.DomHandler(function(error, dom) {
  if (error) {
    console.log('Parsing had an error');
    return;
  } else {
    const item = domUtils.findOne(element => {
      const matches = element.attribs.id === 'heading1';
      return matches;
    }, dom);

    if (item) {
      console.log(item.children[0].data);
    }
  }
});

var parser = new htmlparser.Parser(handler);
parser.write(file);
parser.end();

您将得到的输出是“Some Heading”。但是,在我看来,您会发现使用专用的查询库会更容易。当然,您不需要这样做,但您可以注意到以下代码是多么简单: How do I get an element name in cheerio with node.js

Cheerio 或 querySelector API,例如 https://www.npmjs.com/package/node-html-parser如果您更喜欢 native 查询选择器,它会更加精简。

您可以将该代码与更精简的代码进行比较,例如支持简单查询的 node-html-parser:

const { parse } = require('node-html-parser');

const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';
const root = parse(file);
const text = root.querySelector('#heading1').text;
console.log(text);

关于javascript - 在 Node.js 中使用 htmlparser2 选择 html Node 的文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318315/

相关文章:

parsing - 元描述标签,包括电子邮件

javascript - 将 id 解析为 Bootstrap 模式

javascript - 如何存储图像的 src 并将其与 Cypress 中的另一个图像进行比较?

javascript - 为 REST 端点返回不同的 HTTP 响应代码

node.js - 在 nodejs 和 babel 上使用 es6 的区别

python - 将多种日期格式转换为一种格式python

javascript - AngularJS ng-repeat 具有多个显示不同值的列表

javascript - AngularJS - 将变量传递到 `$routeProvider`

javascript - 如何将对象数组与 sinon.js 匹配?

python - Maltparser 在 NLTK 中给出错误