【问题标题】:C# HTML Agility Pack with IF statement带有 IF 语句的 C# HTML 敏捷包
【发布时间】:2011-12-28 21:28:47
【问题描述】:

我有这段代码,我需要运行 if 语句来设置变量的值。问题是当第一个条件为空时,它会失败。谁能告诉我我做错了什么?

IF 语句位于 foreach 循环中,它在每次迭代时向列表中添加一个值。

非常感谢!

 string result = string.Empty;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";

        using (var stream = request.GetResponse().GetResponseStream())
        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(new StringReader(result));
        HtmlNode root = doc.DocumentNode;

        string itemdesc = doc.DocumentNode.SelectSingleNode("//h1[@class='producttitle']").InnerText;

        HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='resultsset']/table/tbody[@class='result']/tr");

        List<string> sellers = new List<string>();
        List<string> prices = new List<string>();

        foreach (HtmlNode node in nodes)
        {
            string seller = string.Empty;
                if(node.SelectSingleNode(".//ul[@class='sellerInformation']/img").GetAttributeValue("alt", string.Empty) != null)
                {
                    seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/img").GetAttributeValue("alt", string.Empty);
                }

                else if (node.SelectSingleNode(".//ul[@class='sellerInformation']/a/img").GetAttributeValue("alt", string.Empty) != null)
                {
                    seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/a/img").GetAttributeValue("alt", string.Empty);
                }

                else
                {
                    seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/li/div/span/a/b").InnerText;
                }


            sellers.Add(seller);
            string price = node.SelectSingleNode(".//span[@class='price']").InnerText;
            prices.Add(price);

        }

【问题讨论】:

    标签: c# html-parsing web-scraping html-agility-pack


    【解决方案1】:

    可能SelectSingleNode 正在返回null,因此对GetAttributeValue 的调用是一个null 引用问题。在检查属性之前,您需要检查SelectSingleNode 的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2011-07-16
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      相关资源
      最近更新 更多