1

我用于解析 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();

谁能帮帮我?

4

2 回答 2

3

我想你正在寻找这样的东西:

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();
于 2012-11-22T23:28:04.993 回答
1

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

result.DocumentNode.SelectSingleNode("//table/tr[1]")
于 2012-11-22T21:54:54.697 回答