如何使用htmlagilitypack从HTML中提取文本?

3

我想从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”的文本?

2个回答

7
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;

不太漂亮但应该能够工作


3

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;

你如何显示单元格文本? - Cocoa Dev
请使用innerText或者在xpath中使用text(),例如"//td[@class='title']/a/text()"。 - Iman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接