我有一个要解析的 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>no-reply@somemail.net</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>someone@outlook.com</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; }
}
最佳答案
可以编写如下代码:
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++;
}
为了使这段代码简单,我假设了一些事情:
- 电子邮件始终位于 tr 中包含 onlink 属性的第一个 td
- 每个具有 onlink 属性的 tr 都包含一个电子邮件
如果这些条件不适用,此代码将不起作用,它可能会抛出一些异常 (IndexOutOfRangeExceptions),或者它可能会匹配具有错误电子邮件地址的链接。
关于c# - 使用 agility pack 解析 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35434519/