我有这样的事情:
class MyTask
{
public MyTask(int id)
{
Id = id;
IsBusy = false;
Document = new HtmlDocument();
}
public HtmlDocument Document { get; set; }
public int Id { get; set; }
public bool IsBusy { get; set; }
}
class Program
{
public static void Main()
{
var task = new MyTask(1);
task.Document.LoadHtml("http://urltomysite");
if (task.Document.DocumentNode.SelectNodes("//span[@class='some-class']").Count == 0)
{
task.IsBusy = false;
return;
}
}
}
现在,当我启动程序时,它会在if
文件上引发错误,并说Object reference not set to an instance of an object.
。为什么不加载我的页面?我在这里做错了什么?
答案 0 :(得分:18)
您正在寻找.Load()
。
.LoadHtml()
期望获得物理HTML。您正在建立一个网站:
HtmlWeb website = new HtmlWeb();
HtmlDocument rootDocument = website.Load("http://www.example.com");
答案 1 :(得分:1)
如果.SelectNodes("//span[@class='some-class']")
没有返回任何节点且null
,则对其执行Count
会产生此异常。
尝试
if (task.Document.DocumentNode.SelectNodes("//span[@class='some-class']") != null &&
task.Document.DocumentNode.SelectNodes("//span[@class='some-class']").Count == 0)
{
task.IsBusy = false;
return;
}