Winforms HtmlAgilityPack返回null

Winforms HtmlAgilityPack返回null,winforms,c#-4.0,html-agility-pack,Winforms,C# 4.0,Html Agility Pack,我有一个由HtmlAgilityPack编写的程序,它不能正常工作。 Url和节点是正确的。但是它有一个错误,它引用了foreach 错误是 对象引用未设置为对象的实例 它以前起过作用。我删除HtmlAgilityPack dll并再次添加它。但是不起作用。 我需要访问标签的href 我的代码是: string source = wc.DownloadString("http://example.com"); HtmlAgilityPack.HtmlDocument document = ne

我有一个由HtmlAgilityPack编写的程序,它不能正常工作。 Url和节点是正确的。但是它有一个错误,它引用了foreach

错误是

对象引用未设置为对象的实例

它以前起过作用。我删除HtmlAgilityPack dll并再次添加它。但是不起作用。 我需要访问标签的href

我的代码是:

string source = wc.DownloadString("http://example.com");

HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(source);
foreach (HtmlNode div in 
         document.DocumentNode.SelectNodes("//div[@class='test']/a"))
{
//do something
}
很荣幸,这是带有空引用检查的代码:

string source = wc.DownloadString("http://example.com");

HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(source);

var documentNode = document.DocumentNode;
if ( documentNode!=null )
{
    var nodes = documentNode.SelectNodes("//div[@class='test']/a");
    if ( nodes!=null )
    {
        foreach (HtmlNode div in nodes)
        {
            // Do something...
        }
    }
}

SelectNodes
如果找不到节点,则返回null。您必须将
SelectNodes
函数的结果分配给某个变量,并检查它是否为空。你可以检查这个问题。如果它以前工作过-那么可能HTML结构已经更改,因此需要编写新的XPath表达式。它不工作。HTML结构没有改变它会引发相同的异常吗?添加完整的异常详细信息。如果(document.DocumentNode!=null)添加检查
。它没有任何效果