【问题标题】:HTMLAgilityPack node name filter doesn't workHTMLAgilityPack 节点名称过滤器不起作用
【发布时间】:2013-01-28 21:46:05
【问题描述】:

我想使用HTMLAgilityPack 获取页面的文本。我有一些代码:

HtmlAgilityPack.HtmlWeb TheWebLoader = new HtmlWeb();
HtmlAgilityPack.HtmlDocument TheDocument = TheWebLoader.Load(textBox1.Text);

List<string> TagsToRemove = new List<string>() { "script", "style", "link", "br", "hr" };

var Strings = (from n in TheDocument.DocumentNode.DescendantsAndSelf()
               where !TagsToRemove.Contains(n.Name.ToLower())
               select n.InnerText).ToList();

textBox2.Lines = Strings.ToArray();

问题是,它也返回了script 标签的内容。我不知道为什么会这样。有人可以帮帮我吗?

【问题讨论】:

    标签: c# linq c#-4.0 html-agility-pack


    【解决方案1】:

    您的问题来自 InnerText 没有返回您所期望的事实。

    在:

    <A>
        Text1
        <B>Text2</B>
    </A>
    

    返回:

    Text1
    Text2
    

    然后,例如,对于根节点,执行document.DocumentNode.InnerText 将提供script 中的所有文本等...

    我建议你删除所有你不想要的标签:

    foreach (HtmlNode nodeToRemove in (from descendant in TheDocument.DocumentNode.Descendants()
                                       where TagsToRemove.Contains(descendant.Name)
                                       select descendant).ToList())
        nodeToRemove.Remove();
    

    然后获取文本元素的列表:

    List<string> Strings = (from descendant in TheDocument.DocumentNode.DescendantsAndSelf().OfType<HtmlTextNode>()
                            select descendant.InnerText).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      相关资源
      最近更新 更多