Html Agility Pack SelectSingleNode在迭代中总是给出相同的结果?

c# html html-agility-pack selectsinglenode

我想要集合中的节点,但迭代SelectSingleNode我继续获得相同的对象只是node.Id正在改变...我尝试的是读出给定网站的web响应并捕获一些信息,如值,链接.. in特殊定义的元素。

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>

一般承认的答案

通过写作

node.SelectSingleNode("//span[@itemprop='name']").InnerText

就像你写作一样

doc.DocumentNode.SelectSingleNode("//span[@itemprop='name']").InnerText

要做你想做的事,你应该这样写: node.SelectSingleNode(".//span[@itemprop='name']").InnerText

这个. dot / period告诉在当前节点上搜索,而不是在doc上搜索node



许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因