SelectSingleNode and SelectNodes XPath syntax

本文关键字:syntax XPath SelectNodes and SelectSingleNode | 更新日期: 2023-09-27 18:26:44

我的问题与此问题非常相似。在C#中的节点内搜索XmlNode.SelectSingleNode语法

我正在尝试使用HTML敏捷包来拉价格/条件/运费。。。以下是我正在抓取的URL:http://www.amazon.com/gp/offer-listing/0470108541/ref=dp_olp_used?ie=UTF8&条件=所有

以下是我的代码片段:


    string results = "";
    var w = new HtmlWeb();
    var doc = w.Load(url);
    var nodes = doc.DocumentNode.SelectNodes("//div[@class='a-row a-spacing-medium olpOffer']");
    if (nodes != null)
    {
         foreach (HtmlNode item in nodes)
         {
              var price = item.SelectSingleNode(".//span[@class='a-size-large a-color-price olpOfferPrice a-text-bold']").InnerText;
              var condition = item.SelectSingleNode(".//h3[@class='a-spacing-small olpCondition']").InnerText;
              var price_shipping = item.SelectSingleNode("//span[@class='olpShippingPrice']").InnerText;
              results += "price " + price + " condition " + condition + " ship " + price_shipping + "'r'n";
         }
    }
    return results;

无论我尝试哪种组合。//和和。/和/等等…我无法得到我想要的东西(刚才试图学习xpath),而且目前它只是一遍又一遍地返回第一个项目,就像我之前提到的原始问题一样。我想我对选择节点是如何工作的和/或什么是节点缺乏基本的理解。


更新


好的,我已经更改了URL以指向另一本书,前两项工作如预期。。。当我试图将第三项(price_shipping)更改为".//"时,绝对不会从任何内容中提取任何信息。这一定是因为有时甚至没有运输价格,而且这个跨度被省略了。我该如何处理?我试过如果价格发货=无效的


更新


已解决。我从price_shipping中删除了".inerText",当它为空时会引起问题。。。然后我做了空检查,然后可以安全地使用.InerText.

SelectSingleNode and SelectNodes XPath syntax

已解决。我从price_shipping中删除了".inerText",当它为空时会引起问题。。。然后我做了空检查,然后可以安全地使用.InerText.