我想要集合中的节点,但是迭代SelectSingleNode我只是继续得到同一个对象.Id正在改变... 我尝试的是读出给定网站的web响应,并在特殊定义的元素中捕获一些信息,如值,链接..
int offSet = 0;
string address = "http://www.testsite.de/ergebnisliste.html?offset=" + offSet;
HtmlWeb web = new HtmlWeb();
//web.OverrideEncoding = Encoding.UTF8;
HtmlDocument doc = web.Load(address);
HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//div[@itemtype='http://schema.org/Posting']");
foreach (HtmlNode node in collection) {
string id = HttpUtility.HtmlDecode(node.Id);
string cpname = HttpUtility.HtmlDecode(node.SelectSingleNode("//span[@itemprop='name']").InnerText);
string cptitle = HttpUtility.HtmlDecode(node.SelectSingleNode("//span[@itemprop='title']").InnerText);
string cpaddress = HttpUtility.HtmlDecode(node.SelectSingleNode("//span[@itemprop='addressLocality']").InnerText);
string date = HttpUtility.HtmlDecode(node.SelectSingleNode("//div[@itemprop='datePosted']").InnerText);
string link = "http://www.testsite.de" + HttpUtility.HtmlDecode(node.SelectSingleNode("//div[@class='h3 title']//a[@href]").GetAttributeValue("href", "default"));
}
这是例如1次迭代:
<div id="66666" itemtype="http://schema.org/Posting">
<div>
<a>
<img />
</a>
</div>
<div>
<div class="h3 title">
<a href="/test.html" title="Test">
<span itemprop="title">Test</span>
</a>
</div>
<div>
<span itemprop="name">TestName</span>
</div>
</div>
<div>
<div>
<div>
<div>
<span itemprop="address">Test</span>
</div>
<span>
<a>
<span><!-- --></span>
<span></span>
</a>
</span>
</div>
</div>
<div itemprop="date">
<time datetime="2013-03-01">01.03.13</time>
</div>
</div>
答案 0 :(得分:36)
写作
node.SelectSingleNode("//span[@itemprop='name']").InnerText
就像你写作
doc.DocumentNode.SelectSingleNode("//span[@itemprop='name']").InnerText
要做你想做的事,你应该这样写:node.SelectSingleNode(".//span[@itemprop='name']").InnerText
。
这个.
点/句点告诉您在当前节点上搜索node
而不是doc