HtmlAgilityPack无法获取字符串索引器(HtmlAgilityPack cant get string indexer)
我想使用HTML Agility Pack解析HTML
当我用int搜索索引时,我得到了结果。
HtmlWeb htmlWeb = new HtmlWeb(); HtmlDocument htmlDocument = htmlWeb.Load("http://www.timeanddate.com/worldclock/georgia/tbilisi"); var s1 = htmlDocument.DocumentNode.Descendants().Where(x => x.HasAttributes && x.Attributes[0].Value == "ct");但是当我想用字符串索引器搜索属性时,我会得到一个例外。
var s2 = htmlDocument.DocumentNode.Descendants().Where(a => a.HasAttributes && a.Attributes["id"].Value == "ct");当我不使用LINQ并使用谓词委托everithing是好的。
Predicate<HtmlNode> pred = new Predicate<HtmlNode>(forpred); List<HtmlNode> ss = htmlDocument.DocumentNode.Descendants().ToList().FindAll(pred); public static bool forpred(HtmlNode node) { if (node.HasAttributes) { foreach (HtmlAttribute atribute in node.Attributes) { if (atribute.Name == "id" && atribute.Value == "ct") { return true; } } } return false; } //s1.ToList()[0].InnerHtml //s2.ToList()[0].InnerHtml //ss[0].InnerHtmli want to parse HTML Using HTML Agility Pack
When i am searching index with int i am getting result.
HtmlWeb htmlWeb = new HtmlWeb(); HtmlDocument htmlDocument = htmlWeb.Load("http://www.timeanddate.com/worldclock/georgia/tbilisi"); var s1 = htmlDocument.DocumentNode.Descendants().Where(x => x.HasAttributes && x.Attributes[0].Value == "ct");But when i want to search atribute with string indexer i get an exeption.
var s2 = htmlDocument.DocumentNode.Descendants().Where(a => a.HasAttributes && a.Attributes["id"].Value == "ct");And when i dont use LINQ and use predicate delegate everithing is Ok.
Predicate<HtmlNode> pred = new Predicate<HtmlNode>(forpred); List<HtmlNode> ss = htmlDocument.DocumentNode.Descendants().ToList().FindAll(pred); public static bool forpred(HtmlNode node) { if (node.HasAttributes) { foreach (HtmlAttribute atribute in node.Attributes) { if (atribute.Name == "id" && atribute.Value == "ct") { return true; } } } return false; } //s1.ToList()[0].InnerHtml //s2.ToList()[0].InnerHtml //ss[0].InnerHtml最满意答案
因为某些跨度具有属性但不具有id 。 你的代码可以是这样的:
var s2 = htmlDocument.DocumentNode .Descendants() .Where(a => a.Attributes["id"]!=null && a.Attributes["id"].Value == "ct") .ToList();Because some spans have attributes but not id. Your code can be like this:
var s2 = htmlDocument.DocumentNode .Descendants() .Where(a => a.Attributes["id"]!=null && a.Attributes["id"].Value == "ct") .ToList();更多推荐
发布评论