htmlagilitypack link.attributes NullReferenceException

htmlagilitypack link.attributes NullReferenceException

抱歉重复了,但这个似乎不同。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace GetLinks
{
class Program
{
static void Main(string[] args)
{
HtmlDocument doc = new     
HtmlWeb().Load("http://en.wikipedia.org/wiki/Language&#8221");
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a"))
{
Console.WriteLine(link.InnerText);
Console.WriteLine(link.Attributes["href"].Value);
}
Console.ReadKey();
}
}

}

所以我正在使用 htmlagilitypack 并且出现错误:

Console.WriteLine(link.Attributes["href"].Value);

这是错误消息:

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=ConsoleApplication2
  StackTrace:
   at GetLinks.Program.Main(String[] args) in C:\Users\...\Documents\Visual Studio 2010\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 17
   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: 

如何解决这些问题?我尝试创建一个对象实例,但没有成功。

问题是您正在尝试从空值对象访问 属性,因此您需要做的就是在继续您的代码之前检查它是否正常

将该行更改为

var href=link.Attributes["href"];
if (href!=null) Console.WriteLine(href.Value);

希望对您有所帮助。