如何从 html 文件中删除 javascript 并保留纯文本

如何从 html 文件中删除 javascript 并保留纯文本

我正在尝试调整以下脚本以从计算机上的文本文件“input.txt”获取输入并将结果输出到文本文件“output.txt”。

该脚本可以很好地从互联网上获取 html,但我无法弄清楚我需要的适应。

奇怪的是我一年前就想出来了 - 但我不记得我做了什么 - 我不是程序员。

代码:

url='http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags'
curl -s  "$url"   |
sed -Ene:n -etD   \
    -e's/ ?[^ "]*"[^"]*"//g;/"/'bN  \
    -e's/[[:space:]]*($|<)/\n\1/'   \
    -e'/^Moderator.s Note/q'        \
    -e'/.\n/P;/\n</!t'        -e:D  \
    -e'/\n/D;/^<script>/!s/>/&\n/'  \
    -e'/\n/!s/<\/script>/\n/' -e:N  \
    -e'/\n/!{N;s///;}' -e//tD -etn

答案1

如何从 html 文件中删除 javascript 并保留纯文本?

这是一个有趣的问题,因为我认为它突出了使用正则表达式解析标记和可维护性的另一个问题。

如果您的系统上有可用的 php,此脚本将执行此操作

#!/usr/local/bin/php
# point the #! to wherever your PHP commandline binary is

<?php

error_reporting(1);

$html = file_get_contents('http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags');

// create an object representing the DOM tree of the webpage
$document = new DOMDocument;
$document->loadHTML($html);

// store the <script> elements as a DOMN
$script_nodes = $document->getElementsByTagName('script');

// For some reason you can't use the DOMNode::removeChild method
// when iterating through an instance of PHP's DOMNodeList
// so use an array to queue the values in. see
// http://php.net/manual/en/domnode.removechild.php
$scripts_to_remove = [];
for ( $i=0; $i < $script_nodes->length; $i++ ) {
    $scripts_to_remove[] = $script_nodes->item($i);
}

// now we can iterate through the <script> nodes removing them
foreach ( $scripts_to_remove  as $s_node ) {
    $parent = $s_node->parentNode;
    $parent->removeChild($s_node);
}

// print out the new DOM as HTML
echo $document->saveHTML();

用法

要使用该脚本,请设置一个包含上述代码的文件,使其可执行,运行它并将输出重定向到一个文件中,该文件应包含去除标签的 HTML <script>

相关内容