htmlagilitypack链接.属性得到NullReferenceException
本文关键字:NullReferenceException 属性 链接 htmlagilitypack | 更新日期: 2023-09-27 18:17:15
很抱歉有重复,但这个看起来不一样。
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”");
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a"))
{
Console.WriteLine(link.InnerText);
Console.WriteLine(link.Attributes["href"].Value);
}
Console.ReadKey();
}
}
}
所以我使用htmllagilitypack,我得到了错误:
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);
我希望它会有帮助。