【问题标题】:Selecting an html node's text content with htmlparser2 in Node.js在 Node.js 中使用 htmlparser2 选择 html 节点的文本内容
【发布时间】: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


【解决方案1】:

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

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 或 https://www.npmjs.com/package/node-html-parser 之类的 querySelector API 更精简。

您可以将该代码与更精简的代码进行比较,例如支持简单查询的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);

【讨论】:

  • node-html-parser 模块看起来确实更友好。感谢您按原样解决问题并提供替代方案。非常感谢!
猜你喜欢
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多