HtmlAgilityPack - Get DIV content

c# html html-agility-pack scrape string

Question

I am trying to get some text out of a DIV with HtmlAgilityPack in WinForms C#.

My code is:

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml("http://www.tibia.com/news/?subtopic=latestnews");
var res = doc.DocumentNode.SelectSingleNode("//div[@id='PlayersOnline']");
var content = res.InnerHtml;

// Print content
MessageBox.Show(content);

The content I am trying to get is from: http://www.tibia.com/news/?subtopic=latestnews

At the top-right of the website there is a box that says the amount of "Players Online". I want to get that amount.

The HTML on the website looks like this:

<div id="PlayersOnline" onclick="window.location = 'https://secure.tibia.com/community/?subtopic=worlds';">11723<br>Players Online</div>

So I want to get 11723 as output. It wouldn't matter if i get the entire: 11723<br>Players Online as output. i could just regex match later on or split string or something, to ignore the br tag.

But none of my code is working and i don't know why. the application crashes and says

System.NullReferenceException: 'Object reference not set to an instance of an object.'

<res>5__8 was null.

Popular Answer

Try InnerText instead of InnerHtml

var content = doc.DocumentNode.SelectSingleNode("//div[@id='PlayersOnline']").InnerText;



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why