【问题标题】:html agility pack Object reference not set to an instance of an objecthtml敏捷包对象引用未设置为对象的实例
【发布时间】:2012-11-11 07:16:12
【问题描述】:

我用于解析 html 使用 Html Agility Pack 和 Grate 的东西 但我遇到了一些不好的事情:| 这是我的后台代码

public static HtmlDocument GetXHtmlFromUri2(string uri)
    {
        HttpClient client = HttpClientFactory.Create(new CustomeHeaderHandler());


        var htmlDoc = new HtmlDocument()
                                   {
                                       OptionCheckSyntax = true,
                                       OptionFixNestedTags = true,
                                       OptionAutoCloseOnEnd = true,
                                       OptionReadEncoding = true,
                                       OptionDefaultStreamEncoding = Encoding.UTF8,
                                   };

        htmlDoc.LoadHtml(client.GetStringAsync(uri).Result);

        return htmlDoc;

    }

我为 WebApi (Mvc4) 使用 html 敏捷性,这是 Get Method Logic

//GET api/values
    public string GetHtmlFlights()
    {

        var result = ClientFlightTabale.GetXHtmlFromUri2("http://ikiafids.ir/departureFA.html");
        HtmlNode node = result.DocumentNode.SelectSingleNode("//table[1]/tbody/tr[1]");

        string temp = node.FirstChild.InnerHtml.Trim();

        return temp;

    }

但是当我调用这个方法(从浏览器和提琴手)遇到异常时,这个主题:

对象引用未设置为对象的实例,而这个异常与这一行有关

string temp = node.FirstChild.InnerHtml.Trim();

谁能帮帮我?

【问题讨论】:

    标签: c# asp.net-web-api html-agility-pack


    【解决方案1】:

    我认为你的选择器是错误的。试试这个?

    result.DocumentNode.SelectSingleNode("//table/tr[1]")
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找这样的东西:

      var result = ClientFlightTabale.GetXHtmlFromUri2("http://ikiafids.ir/departureFA.html");
      var tableNode = result.DocumentNode.SelectSingleNode("//table[1]");
      
      var titles = tableNode.Descendants("th")
                          .Select(th => th.InnerText)
                          .ToList();
      
      var table = tableNode.Descendants("tr").Skip(1)
                          .Select(tr => tr.Descendants("td")
                                          .Select(td => td.InnerText)
                                          .ToList())
                          .ToList();
      

      【讨论】:

      • 如何将任何 td 归因于特定属性?
      • td.Attributes["someattribute"].Value
      • sry 但我希望将每个元素 (td) 分配给一个属性,例如 Model.FlightID
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      相关资源
      最近更新 更多