如何使用 C# 从 HTML 页中删除<脚本>标记

How to remove <script> tags from an HTML page using C#?

本文关键字:脚本 标记 删除 何使用 HTML      更新时间:2023-09-26
<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            if (window.self === window.top) { $.getScript("Wing.js"); }
        </script>
   </head>
</html>

C#中有没有办法修改上面的HTML文件并将其转换为以下格式:

<html>
    <head>
    </head>
</html>

基本上,我的目标是从HTML页面中删除所有JavaScript。我不知道修改HTML文件的最佳方法是什么。我想以编程方式执行此操作,因为有数百个文件需要修改。

可以使用正则表达式来完成:

Regex rRemScript = new Regex(@"<script[^>]*>['s'S]*?</script>");
output = rRemScript.Replace(input, "");

可能值得一看: HTML Agility Pack

编辑:特定工作代码

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string sampleHtml = 
    "<html>" +
        "<head>" + 
                "<script type='"text/javascript'" src='"jquery.js'"></script>" +
                "<script type='"text/javascript'">" + 
                    "if (window.self === window.top) { $.getScript('"Wing.js'"); }" +
                "</script>" +
        "</head>" +
    "</html>";
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(sampleHtml));
doc.Load(ms);
List<HtmlNode> nodes = new List<HtmlNode>(doc.DocumentNode.Descendants("head"));
int childNodeCount = nodes[0].ChildNodes.Count;
for (int i = 0; i < childNodeCount; i++)
    nodes[0].ChildNodes.Remove(0);
Console.WriteLine(doc.DocumentNode.OuterHtml);

我认为正如其他人所说,HtmlAgility包是最好的途径。我用它来擦和删除大量难以逼角的情况。但是,如果您的目标是一个简单的正则表达式,那么也许您可以尝试 <script(.+?)*</script> .这将删除讨厌的嵌套javascript以及正常的东西,即链接中提到的类型(用于提取脚本标签的正则表达式):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        if (window.self === window.top) { $.getScript("Wing.js"); }
    </script>
    <script> // nested horror
    var s = "<script></script>";
    </script>
</head>
</html>

用法:

Regex regxScriptRemoval = new Regex(@"<script(.+?)*</script>");
var newHtml = regxScriptRemoval.Replace(oldHtml, "");
return newHtml; // etc etc

这似乎是一个奇怪的解决方案。

如果您不想使用任何第三方库来执行此操作,并且不需要实际删除脚本代码,只需禁用它,您可以这样做:

html = Regex.Replace(html , @"<script[^>]*>", "<!--");
html = Regex.Replace(html , @"<'/script>", "-->");

这会从脚本标记中创建 HTML 注释。

使用正则表达式:

string result = Regex.Replace(
    input, 
    @"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|'n|'s)*?>", 
    string.Empty, 
    RegexOptions.Singleline | RegexOptions.IgnoreCase
);