2014-12-07 41 views
0

我正在編寫一些代碼來遍歷HTML頁面中的每個元素並提取所有ID和類。C#HtmlDocument抽取類

我目前的代碼能夠提取ID的,但我看不到一種方法來獲取類,有沒有人知道我可以訪問這些?

private void ParseElements() 
    { 
     // GET: Document from Browser 
     HtmlDocument ThisDocument = Browser.Document; 

     // DECLARE: List of IDs 
     List<string> ListIdentifiers = new List<string>(); 

     // LOOP: Through Each Element 
     for (int LoopA = 0; LoopA < ThisDocument.All.Count; LoopA += 1) 
     { 
      // DETERMINE: Whether ID Exists in Element 
      if (ThisDocument.All[LoopA].Id != null) 
      { 
       // ADD: Identifier to List 
       ListIdentifiers.Add(ThisDocument.All[LoopA].Id); 
      } 
     } 
    } 
+0

這一個接近 - 但它返回所有的樣式。我編寫的應用程序使用單獨的樣式表,因此需要類名稱,如果元素不使用類名稱,則此時不需要樣式。 – 2014-12-07 15:32:30

回答

0

您可以獲取每個節點的內部HTML並使用正則表達式來獲取該類。或者你可以嘗試HTML敏捷包。

喜歡的東西...

HtmlAgilityPack.HtmlDocument AgilePack = new HtmlAgilityPack.HtmlDocument(); 

AgilePack.LoadHtml(ThisDocument.Body.OuterHtml); 

HtmlNodeCollection Nodes = AgilePack.DocumentNode.SelectNodes(@"//*"); 

foreach (HtmlAgilityPack.HtmlNode Node in Nodes) 
{ 
    if (Node.Attributes["class"] != null) 
     MessageBox.Show(Node.Attributes["class"].Value); 

}