【问题标题】:Remove all web textual content keeping only HTML?删除所有仅保留 HTML 的 Web 文本内容?
【发布时间】:2014-03-11 05:39:21
【问题描述】:

需要从 html 文件中删除所有 web 内容,只保留 HTML 标签。

可以通过正则表达式或 JavaScript 来完成吗?

之前:

<html>
<head>
<title>Ask a Question - Stack Overflow</title>
<link rel="shortcut icon" href="//cdn.sstatic.net/stackoverflow/img/favicon.ico">
<script type="text/javascript">
document.write("Code remains un-touched");
</script>
</head>
<body class="ask-page new-topbar">
<div id="first">ONE</div>
<div id="sec">TWO</div>
<div id="third">THREE</div>
</body>
</html>

之后:

<html>
<head>
<title></title>
<link rel="shortcut icon" href="//cdn.sstatic.net/stackoverflow/img/favicon.ico">
<script type="text/javascript">
document.write("Code remains un-touched");
</script>
</head>
<body class="ask-page new-topbar">
<div id="first"></div>
<div id="sec"></div>
<div id="third"></div>
</body>
</html>

更新: 需要使用以后的 HTML 标签,在剥离 web-content 之后,应该显示 html。最后,我对 HTML 代码感兴趣。

【问题讨论】:

  • 您需要检查每个元素是否有内容,如果是,请删除它,
  • 工具可以是任何东西。
  • @j08691 :无论如何,没问题。

标签: javascript html regex


【解决方案1】:

我认为这样的事情应该可行:

$('*').each(function() {
  $(this).contents().filter(function() {
    return this.nodeType == 3 && this.parentNode.nodeName != 'SCRIPT';
  }).remove();
});

遍历所有元素,查看它们的所有子节点,如果它们是文本节点并且不在 script 内,请杀死它们。

您可以在这个页面上进行测试:P

(Yoshi 的 jQueryless 脚本更快,但写起来更短:P)

编辑:nodeName 大写。哎呀。

编辑 OP 的编辑:这将随后获取源代码:

$('html')[0].outerHTML

您可以使用以下方式显示它:

$('body').text($('html')[0].outerHTML)

再次编辑:另外,如果你想要 jQueryless,你也可以改用 document.documentElement.outerHTML (这样更快 更好)。也适用于 Yoshi 的解决方案。

【讨论】:

  • 看起来不错,让我在一些 html 上测试一下,关于需求,我会回复您。 :)
【解决方案2】:

一个简单的递归函数就可以了:

(function removeTextNodes(el) {
  Array.apply([], el.childNodes).forEach(function (child) {
    if (child.nodeType === 3 && el.nodeName !== 'SCRIPT') {
      // remove the text node
      el.removeChild(child);
    }
    else if (child.nodeType === 1) {
      // call recursive for child nodes
      removeTextNodes(child);
    }
  });
})(document.documentElement);

引用 Amadan:只需使用 document.documentElement.outerHTML 将 html 作为字符串获取。

【讨论】:

  • 是的,它是正确的,但我想要 html 代码,而不是呈现的 html!
  • 但它不适用于此 HTML 源代码:amazon.com/dp/B00009R6X9 HTML 已被覆盖。 HTML DOM 应该保持不变。还有@Amadan
猜你喜欢
  • 2015-11-21
  • 1970-01-01
  • 2014-08-09
  • 2010-11-26
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 2019-10-03
相关资源
最近更新 更多