You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML Agility Pack通过InnerText匹配锚点节点抓取数据

问题

需要从美国联邦机动车安全管理局(FMCSA)数据库中抓取MCS-150 Form Date对应的值,该目标数据无唯一标识,仅能通过其兄弟表头内锚点的InnerText(值为"MCS-150 Form Date:")进行定位。

提供的HTML文档片段:

<TR>
 <TH SCOPE="ROW" class="querylabelbkg" align=right><A class="querylabel" 
 href="saferhelp.aspx#">MCS-150 Form Date:</A>
 </TH>
   <TD class="queryfield" valign=top>06/17/2022&nbsp;</TD>
 <TH SCOPE="ROW" class="querylabelbkg" align=right><A class="querylabel" 
 href="saferhelp.aspx#">MCS-150 Mileage (Year):</A>
 </TH>
  <TD valign=top><FONT style=font-size:80% face=arial color=#0000C0><B>92,087 (2020)&nbsp; 
  </TD>
</TR>

尝试使用SelectSingleNode方法匹配但未成功,相关代码行:

HtmlNode nodesInDiv = htmlDoc.DocumentNode.SelectSingleNode(mcsFormDatePath);
解决方案

完全可以通过XPath定位目标锚点节点,再获取相邻兄弟节点的文本值,以下是可行的实现方案:

1. 编写正确的XPath表达式

通过锚点文本找到对应的<A>节点,再定位到其父<TH>的下一个兄弟<TD>节点,两种可行的XPath写法:

  • 写法一:
    //a[text()='MCS-150 Form Date:']/parent::th/following-sibling::td[1]
    
  • 写法二(更侧重表头节点定位):
    //th[./a[text()='MCS-150 Form Date:']]/following-sibling::td[1]
    

2. C#代码实现

将上述XPath代入SelectSingleNode,获取节点后清理文本内容(去除&nbsp;和多余空格):

string mcsFormDatePath = "//a[text()='MCS-150 Form Date:']/parent::th/following-sibling::td[1]";
HtmlNode dateNode = htmlDoc.DocumentNode.SelectSingleNode(mcsFormDatePath);
if (dateNode != null)
{
    // 清理文本,去除无效空格字符
    string formDate = dateNode.InnerText.Trim().Replace("&nbsp;", "");
    // 输出结果:06/17/2022
    Console.WriteLine(formDate);
}

3. 备选方案(LINQ to HTML)

如果对XPath不熟悉,也可以用HtmlAgilityPack的LINQ查询实现:

var dateNode = htmlDoc.DocumentNode
    .Descendants("a")
    .FirstOrDefault(a => a.InnerText.Trim() == "MCS-150 Form Date:")?
    .ParentNode?
    .NextSibling;
if (dateNode != null)
{
    string formDate = dateNode.InnerText.Trim().Replace("&nbsp;", "");
    Console.WriteLine(formDate);
}

内容的提问来源于stack exchange,提问作者Whaaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:50:26