NullReferenceException using HtmlAgilityPack

3

I'd like to know how many tags <a> exist within div , but the NullReferenceException Exception is raised upon reaching XPath.

var baseURL = "AQUI VAI A MINHA URL";

var client = new HtmlWeb();

var pagina = client.Load(baseURL);

var quantidade = pagina.DocumentNode.SelectNodes("//*[@id='react - root']/section/main/article/div/div[1]/div[1]/a").Count;

Has he failed to get in the way or am I doing something wrong?

    
asked by anonymous 05.07.2016 / 00:05

1 answer

4

The SelectNodes() method returns a null if it does not find any node that meets the specified one. Then the code tries to pick up the count and generates this error. But it may be that you have some previous error to unduly generate the null. This should resolve:

var nos = pagina.DocumentNode.SelectNodes("//*[@id='react - root']/section/main/article/div/div[1]/div[1]/a");
var quantidade = nos == null ? 0 : nos.Count;
    
05.07.2016 / 00:17