为什么我的LINQ语句会抛出异常?

bro*_*oke 0 c# linq linq-to-objects

我正在使用HTML敏捷包来抓取一个网站.我正在寻找包含某些文本的"a"元素的所有div标签.以下是示例代码:

 var showLocations = (from div in document.DocumentNode.Descendants("div")
                                 from a in div.DescendantNodes().Where(x => x.Name == "a")
                                 where a.Attributes["href"].Value.Contains("show_locs=Y")
                                 select a).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)

但是,如果找不到该元素,则不会返回null,而是抛出"Null Reference Exception".这是为什么?

Jim*_*mmy 5

我的猜测是有<a>没有href属性的标签(即锚点而不是链接).试着a.GetAttributeValue("href", "").Contains...改为.