【问题标题】:Get the value from a div using HtmlAgilityPack使用 HtmlAgilityPack 从 div 获取值
【发布时间】:2016-04-21 23:39:40
【问题描述】:

我正在尝试使用 HtmlAgilityPack 从 div 中获取值。 我的htmlcode 是这样的:

我需要在news_content_container div 类中获取值,因为您可以看到图中选择了,所以我使用此代码:

     var response1 = await http.GetByteArrayAsync("http://www.nsfund.ir/news?"+link);
                String source1 = Encoding.GetEncoding("utf-8").GetString(response1, 0, response1.Length - 1);
                source1 = WebUtility.HtmlDecode(source1);
                HtmlDocument resultat1 = new HtmlDocument();
                resultat1.LoadHtml(source1);
               var val = resultat1.DocumentNode.Descendants().Where
  (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("news_content_container"))).ToList().First().InnerText;;

但是结果是空的。

【问题讨论】:

    标签: c# html .net html-parsing html-agility-pack


    【解决方案1】:

    试试这个

    var response1 = await http.GetByteArrayAsync("http://www.nsfund.ir/news?"+link);
                    String source1 = Encoding.GetEncoding("utf-8").GetString(response1, 0, response1.Length - 1);
                    source1 = WebUtility.HtmlDecode(source1);
                    HtmlDocument resultat1 = new HtmlDocument();
                    resultat1.LoadHtml(source1);
                   var val = resultat1.DocumentNode.SelectSingleNode("//div[@class='news_content_container']").InnerText;
    

    【讨论】:

    • 我在最后一行得到这个错误:值不能为空。
    • 我收到了这个错误亲爱的朋友:对象引用未设置为对象的实例。
    • 根据我的假设 div 元素不适用于 DOM 中的“news_content_container”类。这对我有用。
    • @EhsanAkbar 请发布您的“链接”变量的值。
    • @EhsanAkbar 好的,我运行该示例代码,它对我来说很好。在您的情况下,source1 字符串是否包含带有“news_content_container”类的 div?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多