如何使用 HtmlAgilityPack 提取特定 HTML 的文本部分?

How do I extract specific HTML's part of text using HtmlAgilityPack?

在查看某个页面的源代码时,我使用 CTRL-F 查找所有出现的 "id=",这给了我 82 个结果。我想要做的是只提取 "id=" 之后的数字。例如,如果属性是 id=344 那么我只想获取 344 作为字符串并将其添加到列表中。

我现在这样做的方式我没有获得链接我以为我会通过这种方式获得所有链接并在它之后进行过滤但是我得到的是空字符串和一些我想要的文本。我猜做 InnerText 是错误的。

Source View

idsnumbers = new List<string>();
HtmlWeb hw = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = hw.Load("http://www.tapuz.co.il/forums2008/");
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
    idsnumbers.Add(link.InnerText);
}

更新获取空异常:

System.NullReferenceException was unhandled
  _HResult=-2147467261
  _message=Object reference not set to an instance of an object.
  HResult=-2147467261
  IsTransient=false
  Message=Object reference not set to an instance of an object.
  Source=WindowsFormsApplication1
  StackTrace:
       at WindowsFormsApplication1.Form1..ctor() in d:\C-Sharp\Tapuz Images\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 50
       at WindowsFormsApplication1.Program.Main() in d:\C-Sharp\Tapuz Images\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

您应该从属性中读取 ID。 InnerText 仅用于标签 内的 文本,位于左括号和右括号之间。所以:

foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
    idsnumbers.Add(link.Attributes["id"].Value);
}

如果你只想进一步从 id 中提取数字,你可以使用 RegExint.TryParse