htmlagilitypack - 删除脚本和样式?

Jac*_*ine 16 c# html-agility-pack

我使用以下方法提取文本格式html:

    public string getAllText(string _html)
    {
        string _allText = "";
        try
        {
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(_html);


            var root = document.DocumentNode;
            var sb = new StringBuilder();
            foreach (var node in root.DescendantNodesAndSelf())
            {
                if (!node.HasChildNodes)
                {
                    string text = node.InnerText;
                    if (!string.IsNullOrEmpty(text))
                        sb.AppendLine(text.Trim());
                }
            }

            _allText = sb.ToString();

        }
        catch (Exception)
        {
        }

        _allText = System.Web.HttpUtility.HtmlDecode(_allText);

        return _allText;
    }
Run Code Online (Sandbox Code Playgroud)

问题是我也得到了脚本和样式标签.

我怎么能排除他们?

L.B*_*L.B 51

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

doc.DocumentNode.Descendants()
                .Where(n => n.Name == "script" || n.Name == "style")
                .ToList()
                .ForEach(n => n.Remove());
Run Code Online (Sandbox Code Playgroud)

  • @Jacqueline` .Where(n => n.Name =="script"|| n.Name =="style"|| n.Name =="#comment")` (7认同)
  • `Name` 属性是否需要不区分大小写进行比较?我认为攻击者可能使用了`<SCRIPT>`。 (2认同)

joh*_*w86 7

您可以使用HtmlDocumentclass 这样做:

HtmlDocument doc = new HtmlDocument();

doc.LoadHtml(input);

doc.DocumentNode.SelectNodes("//style|//script").ToList().ForEach(n => n.Remove());
Run Code Online (Sandbox Code Playgroud)