HtmlAgilityPack獲取所有值

c# html html-agility-pack xpath

我正試圖從網站上獲取價值。這些值在div中,在“主div”下面有更多的div(如果我可以像這樣調用它)。我想要的是獲得那些divs值在“主要div”中。我嘗試使用此代碼:

 string url = "www.examplesite.com";

    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;
        listBox1.Items.Add(cptitle);
    }

網站的結構(在F12運行時)看起來像這樣:

    <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> // <--

對於foreach,我得到“對象引用沒有設置為對象的實例”錯誤...

熱門答案

使用提供的HTML代碼段,您可以使用XPath選擇器直接獲取文本節點:

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>
</div>
</div>
</div>
</div>
</body>";
var document = new HtmlDocument();
document.LoadHtml(html);
var textNodes = document.DocumentNode.SelectNodes(
    "//div[@id='pltexts']/div[@class='plext']/text()"
);
if (textNodes != null)
{
    foreach (var t in textNodes) Console.WriteLine(t.InnerText);
}

輸出:

00
01
02
03
04



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因