HTML敏捷性包的SelectSingleNode给在迭代总是同样的结果?(Html Agility

2019-08-17 07:06发布

我想收藏,但与迭代的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>

Answer 1:

通过写

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

这就像你写

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

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

. 点/周期告诉make在当前节点上的搜索是node而不是在doc



文章来源: Html Agility Pack SelectSingleNode giving always same result in iteration?