HtmlAgilityPack无法获取字符串索引器(HtmlAgilityPack cant get string indexer)

编程入门 行业动态 更新时间:2024-10-25 22:24:19
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].InnerHtml

i 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();

更多推荐

本文发布于:2023-08-07 07:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462027.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   索引   HtmlAgilityPack   string   indexer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!