萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

C# 正則過濾 HTML 代碼:移除腳本、樣式、框架等危險標籤

採集、清洗第三方 HTML 時,需移除 <script>、<iframe>、事件屬性等風險代碼。以下 C# 實現白名單式過濾(示例為黑名單移除,生產建議白名單)。

核心過濾函數

public string CleanHtml(string html) {
    if (string.IsNullOrEmpty(html)) return html;

    // 1. 移除 script 標籤及內容
    html = Regex.Replace(html, @"<script[\s\S]*?</script\s*>", "", RegexOptions.IgnoreCase);
    // 2. 移除 href=javascript: 伪協議
    html = Regex.Replace(html, @"href\s*=\s*[\s\S]*?script\s*:", "", RegexOptions.IgnoreCase);
    // 3. 移除 on* 事件屬性 (onload, onclick 等)
    html = Regex.Replace(html, @"\son\w+\s*=", " _disabled_event=", RegexOptions.IgnoreCase);
    // 4. 移除 iframe
    html = Regex.Replace(html, @"<iframe[\s\S]*?</iframe\s*>", "", RegexOptions.IgnoreCase);
    // 5. 移除 frameset
    html = Regex.Replace(html, @"<frameset[\s\S]*?</frameset\s*>", "", RegexOptions.IgnoreCase);
    // 6. 移除 img 標籤 (按需)
    html = Regex.Replace(html, @"<img[^>]+>", "", RegexOptions.IgnoreCase);
    // 7. 移除 p 標籤 (按需保留文本)
    html = Regex.Replace(html, @"</p>", "", RegexOptions.IgnoreCase);
    html = Regex.Replace(html, @"<p>", "", RegexOptions.IgnoreCase);
    // 8. 通配移除其餘所有標籤
    html = Regex.Replace(html, @"<[^>]*>", "", RegexOptions.IgnoreCase);

    // 9. 清理殘留實體
    html = html.Replace(" ", " ").Replace("</strong>", "").Replace("<strong>", "");
    return html.Trim();
}

關鍵正則解析

  • [\s\S]*?:非貪婪匹配任意字符(含換行),解決 .*? 不匹配換行問題。
  • IgnoreCase:大小寫不敏感。
  • 順序很重要:先移除大塊標籤 (script/iframe),再移除屬性,最後通配清理。

生產級建議:改用白名單 + 成熟庫

// AngleSharp 白名單清洗範例
var config = Configuration.Default.WithCss();
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(req => req.Content(html));
var sanitizer = new HtmlSanitizer(); // 需引用 HtmlSanitizer NuGet
sanitizer.AllowedTags.AddRange(new[] { "p", "br", "b", "strong", "i", "em", "a", "img", "ul", "ol", "li" });
sanitizer.AllowedAttributes.Add("href");
sanitizer.AllowedAttributes.Add("src");
sanitizer.AllowedAttributes.Add("alt");
return sanitizer.Sanitize(html);

HtmlSanitizer、AngleSharp、HtmlAgilityPack 處理巢狀、編碼、實體、條件註釋等邊界情況遠勝手寫正則。

copyright © 萬盛學電腦網 all rights reserved