【问题标题】:node.js \ sanitize html and also remove tagsnode.js \ 清理 html 并删除标签
【发布时间】:2015-10-16 15:58:39
【问题描述】:

我如何告诉"sanitize-html" 实际删除 html 标签(只保留其中的内容)?目前,例如,如果我将其设置为保留 div 部分,则在输出中它还会写入<div>some content</div> - 我只想要内部...('一些内容')

简而言之 - 我不想要标签、属性等 - 只有这些元素的内容..

var Crawler = require("js-crawler");
    var download = require("url-download");
    var sanitizeHtml = require('sanitize-html');
    var util = require('util');
    var fs = require('fs');

    new Crawler().configure({depth: 1})
      .crawl("http://www.cnn.com", function onSuccess(page) {

        var clean = sanitizeHtml(page.body,{
         allowedTags: [ 'p', 'em', 'strong','div' ],
        });
        console.log(clean);
        fs.writeFile('sanitized.txt', clean, function (err) {
            if (err) throw err;
            console.log('It\'s saved! in same location.');
        });

        console.log(util.inspect(clean, {showHidden: false, depth: null}));
        var str = JSON.stringify(clean.toString());
        console.log(str);
        /*download(page.url, './download')
        .on('close', function () {
          console.log('One file has been downloaded.');
        });*/
      });

【问题讨论】:

    标签: node.js html-sanitizing


    【解决方案1】:

    我是 sanitize-html 的作者。

    您可以将 allowedTags 设置为空数组。 sanitize-html 不会丢弃不允许的标签的内容,只会丢弃标签本身(除了一些标签,如“脚本”和“样式”,这对它们没有意义)。否则,它最初的预期用途就没有多大用处,即清理从文字处理器等复制和粘贴到富文本编辑器中的标记。

    但是,如果您有如下标记:

    <div>One</div><div>Two</div>
    

    结果如下:

    一二

    要解决这个问题,您可以使用 textFilter 选项来确保标签的文本始终后跟至少一个空格:

    textFilter: function(text) {
      return text + ' ';
    }
    

    但是,这也会在包含“strong”和“em”等内联标签的句子中引入额外的空格。

    所以我想得越多,对你来说最好的答案可能是一个完全不同的 npm 模块:

    https://www.npmjs.com/package/html-to-text

    它被广泛使用并且比您的用例更适合。 sanitize-html 确实适用于您想要标签的情况......而不是错误的标签。

    【讨论】:

    • 谢谢。这是一个供将来参考的链接:github.com/punkave/sanitize-html
    • 真的很棒的东西。 @Tom Boutell 我正在为我当前的项目使用“sanitize-html”。我这里有个问题,console.log(sanitizeHtml('"Yummy"')); 正在返回"&amp;quot;Yummy&amp;quot;",我不想要&amp;quot;。我怎样才能做到这一点?
    • 请把它放在一个单独的问题中 Jahanzaib。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2011-03-10
    • 2011-02-26
    • 2022-01-19
    • 2016-12-13
    • 2011-05-04
    • 2012-04-13
    • 2011-11-24
    相关资源
    最近更新 更多