使用Windows应用商店应用中的HtmlAgilityPack进行HTML解析

时间:2013-05-19 11:18:04

标签: c# html-parsing windows-store-apps html-agility-pack object-reference

我正在解析HTML代码以在“Windows应用商店应用”中获取图片链接 我正在使用Html Agility Pack! 这里的守则:

    async void LoidContent()
        {
            foreach (var feedItem in feedData.Items)
            {
               HttpClient httpClient  = new HttpClient();
               var stream = await httpClient.GetStreamAsync(feedItem.Link);
               HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.Load(stream);

                // GET IMAGE
                var div = htmlDoc.DocumentNode.Descendants().FirstOrDefault(
                    d =>
                    d.Name == "div" && d.Attributes["class"] != null && d.Attributes["class"].Value == "pika-stage img");

                var img = div.Descendants("img").FirstOrDefault();
                if (img != null)
                {
                    string imgLinks = img.Attributes["src"].Value;
                    feedItem.Image = new Uri(imgLinks);
                }
}}

有时应用程序崩溃 “此对象中未将对象引用设置为对象的实例”

var img = div.Descendants("img").FirstOrDefault();

1 个答案:

答案 0 :(得分:0)

在此之前:

var img = div.Descendants("img").FirstOrDefault();

检查null

if ((div != null) && (div.Descendants("img") != null))
{
    // the rest of your code
}