<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文件的最佳方法。我想以编程方式进行,因为有数百个文件需要修改。
答案 0 :(得分:23)
可以使用正则表达式完成:
Regex rRemScript = new Regex(@"<script[^>]*>[\s\S]*?</script>");
output = rRemScript.Replace(input, "");
答案 1 :(得分:8)
值得一看: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);
答案 2 :(得分:6)
我认为正如其他人所说,HtmlAgility包是最佳途径。我已经使用它来刮并删除难以转角案件的负载。但是,如果一个简单的正则表达式是你的目标,那么也许你可以尝试<script(.+?)*</script>
。这将删除令人讨厌的嵌套javascript以及普通的东西,即链接中引用的类型(Regular Expression for Extracting Script Tags):
<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
答案 3 :(得分:1)
这似乎是一个奇怪的解决方案。
如果你不想使用任何第三方库来执行它而不需要实际删除脚本代码,只需要禁用它,你可以这样做:
html = Regex.Replace(html , @"<script[^>]*>", "<!--");
html = Regex.Replace(html , @"<\/script>", "-->");
这会从脚本标记中创建HTML注释。
答案 4 :(得分:0)
使用正则表达式:
string result = Regex.Replace(
input,
@"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|\n|\s)*?>",
string.Empty,
RegexOptions.Singleline | RegexOptions.IgnoreCase
);