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

时间:2015-10-05 22:27:12

标签: c# .net winforms html-agility-pack

在查看页面的页面源时,我使用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: 

1 个答案:

答案 0 :(得分:1)

您应该从属性中读取ID。 InnerText仅用于 in 标记内的文本,在开始和结束括号之间。所以:

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

如果您想进一步仅从ID中提取数字,可以使用RegExint.TryParse

相关问题