带有IF语句的C#HTML Agility Pack

时间:2011-11-14 18:16:33

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

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

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);

        }

1 个答案:

答案 0 :(得分:0)

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