开发者

How to extract text from HTML using htmlagilitypack for this sample?

I wanna extract the text from a HTML source. I'm try开发者_C百科ing with c# and htmlagilitypack dll.

The source is:

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

How can I get the text Here 1 and Here 2 from the table?


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;

not so pretty but should work


Xpath version

 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;

and for the LINQ version just change the var Nodes = .. line with:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜