2016-03-19 9 views
2

Es gibt nicht viele Beispiele für die Verwendung von AngleSharp zum Parsen, wenn Sie keinen Klassennamen oder eine ID verwenden müssen.AngleSharp Parsing

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> 

Ich mag die href von irgendwelchen <a>-Tags zu finden, die einen title = Bing

In Python BeautifulSoup habe ich

item_needed = a_row.find('a', {'title': 'Bing'}) 

verwenden und dann die href greifen Attribut

oder jQuery

a[title='Bing'] 

Aber ich stecke mit AngleSharp z. Beispiel folgende 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); 

Antwort

4

Sieht aus wie es war Problem in Ihrem HTML-Markup, das AngleSharp verursachen konnte das Zielelement, dh die Räume um Winkel-Klammern finden:

<span>< a href = ""bing.com"" title = ""Bing"" >< span class=""icon icon_none""> 

Nachdem der HTML-Code korrigiert wurde, wählen LINQ und CSS-Selektor den Ziellink erfolgreich aus:

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")); 
}