AngleSharp解析

Spe*_*527 5 c# html-parsing anglesharp

当您没有要使用的类名或ID时,找不到使用AngleSharp进行解析的许多示例.

HTML

<span><a href="google.com" title="Google"><span class="icon icon_none"></span></a></span>
<span><a href="bing.com" title="Bing"><span class="icon icon_none"></span></a></span>
<span><a href="yahoo.com" title="Yahoo"><span class="icon icon_none"></span></a></span>
Run Code Online (Sandbox Code Playgroud)

我想从任何<a>标题= Bing的标签中找到href

在Python BeautifulSoup我会用

item_needed = a_row.find('a', {'title': 'Bing'})
Run Code Online (Sandbox Code Playgroud)

然后抓住href属性

或jQuery

a[title='Bing']
Run Code Online (Sandbox Code Playgroud)

但是,我坚持使用AngleSharp,例如.以下示例 https://github.com/AngleSharp/AngleSharp/wiki/Examples#getting-certain-elements

c#AngleSharp

var parser = new AngleSharp.Parser.Html.HtmlParser();
var document = parser.Parse(@"<span><a href=""google.com"" title=""Google""><span class=""icon icon_none""></span></a></span>< span >< a href = ""bing.com"" title = ""Bing"" >< span class=""icon icon_none""></span></a></span><span><a href = ""yahoo.com"" title=""Yahoo""><span class=""icon icon_none""></span></a></span>");

//Do something with LINQ
var blueListItemsLinq = document.All.Where(m => m.LocalName == "a" && //stuck);
Run Code Online (Sandbox Code Playgroud)

har*_*r07 9

看起来HTML标记中存在导致AngleSharp无法找到目标元素(即尖括号周围的空格)的问题:

< span >< a href = ""bing.com"" title = ""Bing"" >< span class=""icon icon_none"">
Run Code Online (Sandbox Code Playgroud)

修复HTML后,LINQ和CSS选择器都成功选择了目标链接:

var parser = new AngleSharp.Parser.Html.HtmlParser();
var document = parser.Parse(@"<span><a href=""google.com"" title=""Google""><span class=""icon icon_none""></span></a></span><span><a href = ""bing.com"" title = ""Bing""><span class=""icon icon_none""></span></a></span><span><a href = ""yahoo.com"" title=""Yahoo""><span class=""icon icon_none""></span></a></span>");

//LINQ example
var blueListItemsLinq = document.All
                                .Where(m => m.LocalName == "a" && 
                                            m.GetAttribute("title") == "Bing"
                                       );

//LINQ equivalent CSS selector example
var blueListItemsCSS = document.QuerySelectorAll("a[title='Bing']");

//print href attributes value to console
foreach (var item in blueListItemsCSS)
{
    Console.WriteLine(item.GetAttribute("href"));
}
Run Code Online (Sandbox Code Playgroud)