我使用了以下代码从web page.But中提取urls,如图中所示
对象引用未设置为对象的实例
异常。有什么问题吗?我该怎么纠正呢?
WebClient client = new WebClient();
string url = "http://www.google.co.in/search?hl=en&q=java&start=10&sa=N";
string source = client.DownloadString(url);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(source);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href and @rel='nofollow']"))
{
Console.WriteLine(link.Attributes["href"].Value);
}发布于 2010-03-20 16:12:41
首先,您应该在文档中查找NullReferenceException。上面写着
当尝试取消引用空对象引用时引发的异常。
这意味着你做了相当于
SomeClass reference = null;
reference.Method(); // or reference.Property;接下来,查看出现错误的代码行,并找出您要删除的内容:
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href and @rel='nofollow']"))doc.DocumentNodedoc.DocumentNode.SelectNodes所以要么doc是空的,要么doc.DocumentNodes是空的。因为您刚刚将HtmlDocument的一个新实例分配给了doc,所以doc不会是问题所在。这意味着您加载了一个空文档,这样就没有doc.DocumentNode。
在循环之前检查doc.DocumentNode是否为null。
发布于 2010-03-20 16:10:29
从哪一行抛出异常;实际的foreach行还是循环的内容?
处理此问题的最简单方法可能是使用调试器--在foreach前面弹出一个断点,当运行时暂停时,检查各种变量的内容,如link、doc.DocumentNode等。如果link为非空,则检查link.Attributes["href"]是否为空,等等。
https://stackoverflow.com/questions/2483738
复制相似问题