Nullreferenceexception using Htmlagilitypack

Asked

Viewed 63 times

3

I wonder how many tags <a> exist within a div, but the Exception NullReferenceException is fired when arriving on 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;

He couldn’t get in the way or I’m doing something wrong?

1 answer

4


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

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

I put in the Github for future reference.

  • I understand, this explained then. Why is he not finding anything? Inside div[1]/a I have three <a> tags and I generated this path in Chrome using the element inspector.

  • Then I can’t say.

  • Yeah, it’s really complicated. All right, thank you very much.

  • 1

    Do you know if this HTML is being generated dynamically by Javascript on the screen? Htmlagilitypack does not execute the snippets of Javascript code you receive from the request, so HTML generated by JS will not be captured by the library. If that’s it Anglesharp has support for a JS engine (only it’s not 100% functional either, but it’s worth a try).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.