我试图从网站上获取价值。这些值在div中,其中更多div在"主要div" (如果我可以这样称呼它)。 我想要的是,让那些div值得在"主要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> // <--
我得到&#34;对象引用未设置为对象的实例&#34; foreach的错误...
答案 0 :(得分:1)
使用提供的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