2016-02-16 103 views
3

解析HTML我有一个HTML解析(见下文)使用敏捷包

<div id="mailbox" class="div-w div-m-0"> 
    <h2 class="h-line">InBox</h2> 
    <div id="mailbox-table"> 
     <table id="maillist"> 
      <tr> 
       <th>From</th> 
       <th>Subject</th> 
       <th>Date</th> 
      </tr> 
      <tr onclick="location='readmail.html?mid=welcome'" style="font-weight: bold;"> 
       <td>[email protected]</td> 
       <td> 
        <a href="readmail.html?mid=welcome">Hi, Welcome</a> 
       </td> 
       <td> 
        <span title="2016-02-16 13:23:50 UTC">just now</span> 
       </td> 
      </tr> 
      <tr onclick="location='readmail.html?mid=T0wM6P'" style="font-weight: bold;"> 
       <td>[email protected]</td> 
       <td> 
        <a href="readmail.html?mid=T0wM6P">sa</a> 
       </td> 
       <td> 
        <span title="2016-02-16 13:24:04">just now</span> 
       </td> 
      </tr> 
     </table> 
    </div> 
</div> 

我需要解析<tr onclick=标签链接和电子邮件地址在<td>标签。

到目前为止,我管理从我的HTML第一次发生电子邮件/链接。

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(responseFromServer); 

有人能告诉我它是如何正确完成的吗?基本上我想要做的是从所有标签中的html中获取所有的电子邮件地址和链接。

foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//tr[@onclick]")) 
{ 
    HtmlAttribute att = link.Attributes["onclick"]; 
    Console.WriteLine(att.Value); 
} 

编辑:我需要将分析的值成对存储在类(列表)中。电子邮件(链接)和发件人电子邮件。

public class ClassMailBox 
{ 
    public string From { get; set; } 
    public string LinkToMail { get; set; }  

} 
+0

我也试过HtmlAgilityPack,但它不支持XPath。 – Fab

+0

您是否尝试过CssPath功能? – Fab

+1

@Tagyoureit我想你的代码,并打印出两个TR项目: 位置= '?readmail.html中旬=欢迎' 位置= '?readmail.html中旬= T0wM6P' 我使用.NET 4.5和HtmlAgilityPack 1.4.9。你能否检查你在responseFromServer变量中获得的html是否完整。 谢谢 – avenet

回答

2

你可以写下面的代码:

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(responseFromServer); 

foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//tr[@onclick]")) 
{ 
    HtmlAttribute att = link.Attributes["onclick"]; 
    ClassMailBox classMailbox = new ClassMailBox() { LinkToMail = att.Value }; 
    classMailBoxes.Add(classMailbox); 
} 

int currentPosition = 0; 

foreach (HtmlNode tableDef in doc.DocumentNode.SelectNodes("//tr[@onclick]/td[1]")) 
{ 
    classMailBoxes[currentPosition].From = tableDef.InnerText; 
    currentPosition++; 
} 

为了保持代码的简单,我假设一些事情:

  1. 电子邮件总是在内部首款TD tr其中包含一个onlink属性
  2. 每个带有onlink属性的tr都包含一个电子邮件

如果这些条件不适用,这段代码将不起作用,它可能会抛出一些异常(IndexOutOfRangeExceptions),或者它可能与具有错误电子邮件地址的链接匹配。

+0

是的,它像一个魅力。谢谢你的时间!你的假设是正确的(1和2)。 – Tagyoureit