【问题标题】:How to extract text from HTML using htmlagilitypack for this sample?对于此示例,如何使用 htmlagilitypack 从 HTML 中提取文本?
【发布时间】:2011-08-17 18:03:48
【问题描述】:

我想从 HTML 源中提取文本。我正在尝试使用 c# 和 htmlagilitypack dll。

来源是:

<table>
  <tr>
    <td class="title">
      <a onclick="func1">Here 2</a>
    </td>
    <td class="arrow">
      <img src="src1" width="9" height="8" alt="Down">
    </td>
    <td class="percent">
      <span>39%</span>
    </td>
    <td class="title">
      <a onclick="func2">Here 1</a>
    </td>
    <td class="arrow">
      <img src="func3" width="9" height="8" alt="Up">
    </td>
    <td class="percent">
      <span>263%</span>
    </td>
  </tr>
</table>

如何从表格中获取文本 Here 1 和 Here 2?

【问题讨论】:

    标签: c# linq xpath html-agility-pack html-content-extraction


    【解决方案1】:

    Xpath 版本

     HtmlDocument doc = new HtmlDocument();
     doc.LoadHtml(t);
    
     //this simply works because InnerText is iterative for all child nodes
     HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//td[@class='title']");
    //but to be more accurate you can use the next line instead
    //HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//td[@class='title']/a");
    
    
     string result;
     foreach (HtmlNode item in nodes) 
           result += item.InnerText;
    

    对于 LINQ 版本,只需将 var Nodes = .. 行更改为:

     var Nodes = from x in htmlDoc.DocumentNode.DescendantNodes()
                      where x.Name == "td" && x.Attributes["class"].Value == "title"
                      select x.InnerText;
    

    【讨论】:

    • 如何显示单元格文本?
    • 使用 innerText 或者你可以像这样在 xpath 中使用 text() "//td[@class='title']/a/text()"
    【解决方案2】:
    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml("web page string");
    var xyz = from x in htmlDoc.DocumentNode.DescendantNodes()
                         where x.Name == "td" && x.Attributes.Contains("class")
                         where x.Attributes["class"].Value == "title"
                         select x.InnerText;
    

    不是很漂亮,但应该可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多