You need to enable JavaScript to run this app. C# 如何使用HTMLAgilityPack提取DIV嵌套标签中的日期文本
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何使用HTMLAgilityPack提取DIV嵌套标签中的日期文本

问题原因

你当前的代码是直接获取id为footer的div的全部内部文本,会把Added in:前缀、多余的换行和空格也一并提取,无法直接拿到纯净的日期内容。

解决方案

方案1:直接定位日期所在的strong标签(推荐)

调整XPath路径直接指向嵌套的strong节点,再调用Trim()方法清除文本首尾的空白字符即可:

var dateNode = doc.DocumentNode.SelectSingleNode("//div[@id='footer']//strong");
if(dateNode != null)
{
    string dateText = dateNode.InnerText.Trim();
}

注:此方案执行效率最高,只要页面结构固定就可以使用,最终拿到的dateText就是07/06/2021 2:15:36 PM。

方案2:正则提取适配结构变化场景

如果页面的标签结构可能变动,可以先拿到footer区域的全部文本,再通过正则匹配日期格式的内容:

using System.Text.RegularExpressions;

string footerText = doc.DocumentNode.SelectSingleNode("//div[@id='footer']").InnerText;
Match dateMatch = Regex.Match(footerText, @"\d{2}/\d{2}/\d{4}\s+\d{1,2}:\d{2}:\d{2}\s+[AP]M");
if(dateMatch.Success)
{
    string dateText = dateMatch.Value;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 06:27:02