繁体   English   中英

如何使用C#从HTML页面中删除<script>标签?

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

<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
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM