【问题标题】:HTML parsing with HtmlAgilityPack in Windows Store App在 Windows Store App 中使用 HtmlAgilityPack 解析 HTML
【发布时间】:2013-05-14 02:23:21
【问题描述】:

我正在解析 HTML 代码以在“Windows 应用商店应用程序”中获取图像链接 我正在使用 Html 敏捷包! 这里是代码:

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

【问题讨论】:

  • 您有时是否有没有div 元素的文档?或者没有 pika-stage img 类?
  • 不!所有文档都遵循相同的模板(由 CMS 生成)。
  • 这可能是 div 没有 img 后代。您有要测试的示例 HTML 吗?

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


【解决方案1】:

在此之前:

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

检查null

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2016-11-20
    • 2010-12-03
    相关资源
    最近更新 更多