【问题标题】:Html Agility Pack: how to parse a webresponse and get a specified html element in c#Html Agility Pack:如何在c#中解析webresponse并获取指定的html元素
【发布时间】:2012-05-03 15:10:54
【问题描述】:

我用谷歌搜索了我的问题,发现 Html Agility Pack 可以在 c# 中解析 html。但是没有好的例子,我不能用它来达到我的目的。我有一个html document,它有这样的部分:

<div class="pray-times-holder">
    <div class="pray-time">
        <div class="labels">
            Time1:</div>
        04:28:24
    </div>
    <div class="pray-time">
        <div class="labels">
            Time2:</div>
        06:04:41
    </div>
</div>

我想获取Time1Time2 的值。例如Time1 的值 04:28:24Time2 的值 06:04:41 我想得到这些值。你能帮帮我吗?

【问题讨论】:

  • 您对 XmlDocument 类和 XPath 的熟悉程度如何? HAP 有一个非常相似的界面。
  • @Cameron 不,不幸的是我不熟悉 xpath。你能帮帮我吗?

标签: c# html parsing html-agility-pack


【解决方案1】:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

var results = doc.DocumentNode
    .Descendants("div")
    .Where(n => n.Attributes["class"] != null && n.Attributes["class"].Value == "pray-time")
    .Select(n => n.InnerText.Replace("\r\n","").Trim())
    .ToArray();

【讨论】:

    【解决方案2】:

    此控制台应用程序代码:

     HtmlDocument doc = new HtmlDocument();
     doc.Load(yourHtml);
     foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class = 'labels']"))
     {
         Console.WriteLine(node.NextSibling.InnerText.Trim());
     }
    

    会输出这个:

    04:28:24
    06:04:41
    

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 1970-01-01
      • 2011-01-16
      • 2013-08-21
      • 2012-11-26
      • 1970-01-01
      • 2013-05-04
      • 2018-12-03
      • 2011-06-12
      相关资源
      最近更新 更多