我为了解析 html 使用 Html Agility Pack 等等 Grate stuff 但是我遇到了一些不好的事情:| 这是我的后台代码
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 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;
}
但是当我(从浏览器和 Fiddler)调用这个方法时遇到异常,主题是:
对象引用未设置到对象的实例,此异常与此行有关
string temp = node.FirstChild.InnerHtml.Trim();
有人能帮帮我吗?
最佳答案
我认为您正在寻找这样的东西:
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();
关于c# - html 敏捷包对象引用未设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520346/