HtmlAgilityPack getting all value inside a

c# html html-agility-pack xpath


I'm trying to get values from a website. The values are inside a div, where's more div under that "main div" (if I can call it like this). What I want to, is to get those divs value thats inside the "main div". I tried with this code:

 string url = "";

    HtmlWeb web = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument doc = web.Load(url);
    HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//div[@id='plex_container']");
    foreach (HtmlNode node in collection)
        string cptitle = node.SelectSingleNode(".//div[@id='pltexts']").InnerText;

The website's structure (while in F12 running-time) looks like this:

    <body onload="initialize()" id="dashboard">
<div id="header">...</div>
     <div id="dashboard_container">
         <div id="comm" class="comm_expanded">
            <div id="pl_header_tab">...</div>
            <div id="pltext_tab">...</div>
            <div id="plex_container">
                <div id="pl_status"></div>
                <div id="pltexts">
                   <div class="plext">...</div> // <-- Im trying to get these values
                   <div class="plext">...</div> // <-- 
                   <div class="plext">...</div> // <-- 
                   <div class="plext">...</div> // <--
                   <div class="plext">...</div> // <--

I'm getting "Object reference not set to an instance of an object" error for the foreach...

Popular Answer

Using the provided HTML snippet, you can use a XPath selector to get the text nodes directly:

var html =
<body onload='initialize()' id='dashboard'>
<div id='header'>...</div>
<div id='dashboard_container'>
<div id='comm' class='comm_expanded'>
<div id='pl_header_tab'>...</div>
<div id='pltext_tab'>...</div>
<div id='plex_container'>
<div id='pl_status'></div>
<div id='pltexts'>
<div class='plext'>00</div>
<div class='plext'>01</div>
<div class='plext'>02</div>
<div class='plext'>03</div>
<div class='plext'>04</div>
var document = new HtmlDocument();
var textNodes = document.DocumentNode.SelectNodes(
if (textNodes != null)
    foreach (var t in textNodes) Console.WriteLine(t.InnerText);




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow