c# - 使用 agility pack 解析 html

标签 c# html parsing html-agility-pack

我有一个要解析的 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++;
}

为了使这段代码简单,我假设了一些事情:

  1. 电子邮件始终位于 tr 中包含 onlink 属性的第一个 td
  2. 每个具有 onlink 属性的 tr 都包含一个电子邮件

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

关于c# - 使用 agility pack 解析 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35434519/

相关文章:

c++ - 我是否错误地使用了 atoi?

c# - 重定向至操作不起作用

c# - 从 sharepoint 2010 服务器读取文件夹和文件属性,例如 UniqueId

javascript - 单击事件到自动事件图像在 Jquery 中更改

html - “base.document.layout”对象没有属性 'header' odoo14 - 尝试在报告中显示自定义字段

javascript - 如何对字符串化的 JavaScript 进行去字符串化?

c# - 统一: Detect if the Return or Done key was pressed in the native iOS keyboard

c# - 如何在c#中启动另一个主窗体

javascript - 数组被视为对象,无法 NgFor

javascript - Webpack 插件解析器找不到本地或模块函数调用