18

我想要集合中的节点,但是通过迭代 SelectSingleNode 我不断得到相同的对象,只是 node.Id 正在改变......我尝试的是读出给定站点的 webresponse 并捕获一些信息,如值、链接......特殊定义的元素。

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>

4

1 回答 1

45

通过写作

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

就像你在写

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

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

这个.点/句号告诉在当前节点上进行搜索,node而不是在doc

于 2013-03-03T12:43:44.907 回答