用HTMLDocumentClass分析Html代碼(以及讀取HtmlElement所有屬性方法)

大家可能經常會需要分析一段Html代碼,有的人可能會用WebBrowser,這個方法不錯,其實微軟還提供了另一個組件,mshtml(引用Microsoft.mshtml,這個可能有好幾個大家記得引用Framework目錄下的那個),這個東西提供分析html代碼的方法,而且用起來非常的方便。

  1. HTMLDocumentClass doc = new HTMLDocumentClass();  
  2. IHTMLDocument2 doc2 = doc;  
  3. doc2.write(html);  //html就是外面傳進來的html代碼  
            HTMLDocumentClass doc = new HTMLDocumentClass();
            IHTMLDocument2 doc2 = doc;
            doc2.write(html);  //html就是外面傳進來的html代碼
使用的時候只需要遞歸doc對象childNodes即可

  1. IHTMLDOMChildrenCollection collect = (IHTMLDOMChildrenCollection)doc.childNodes;  
  2. foreach (IHTMLDOMNode node in collect)  
  3. {  
  4.     //因爲關閉節點也會有(比如</a>,但是這樣的節點會被定義爲HTMLUnknownElementClass)   
  5.     //所以要判斷這個節點是不是未知節點不是才處理   
  6.     if (!(node is HTMLUnknownElementClass))  
  7.     {  
  8.   
  9.  //獲取屬性集合   
  10.         IHTMLAttributeCollection attrs = (IHTMLAttributeCollection)node.attributes;    
  11.         foreach (IHTMLDOMAttribute attr in attrs)  
  12.         {  
  13.   
  14.             //只有specified=true的屬性纔是你要的   
  15.             if (attr.specified)  
  16.             {  
  17.                   
  18.             }  
  19.         }  
  20.     }  
  21. }  
            IHTMLDOMChildrenCollection collect = (IHTMLDOMChildrenCollection)doc.childNodes;
            foreach (IHTMLDOMNode node in collect)
            {
                //因爲關閉節點也會有(比如</a>,但是這樣的節點會被定義爲HTMLUnknownElementClass)
                //所以要判斷這個節點是不是未知節點不是才處理
                if (!(node is HTMLUnknownElementClass))
                {

             //獲取屬性集合
                    IHTMLAttributeCollection attrs = (IHTMLAttributeCollection)node.attributes;  
                    foreach (IHTMLDOMAttribute attr in attrs)
                    {

                        //只有specified=true的屬性纔是你要的
                        if (attr.specified)
                        {
                            
                        }
                    }
                }
            }

順便說一下,IHTMLDOMNode對象其實是所有節點(包括關閉節點比如"</a>"這個也算一個IHTMLDOMNode)

所以大家判斷是不是開頭的節點只要判斷一下是不是不等於HTMLUnknownElementClass

大家如果使用WebBrowser肯能一直有個困惑WebBrowser提供的HtmlElement對象沒有提供Attribute屬性集合,也就無法通過循環獲得節點的所有屬性,其實通過mshtml可以解決這個問題。大家可用DomDocument轉換爲HTMLDocumentClass

  1. WebBrowser wb = new WebBrowser();  
  2. HTMLDocumentClass cls = (HTMLDocumentClass)wb.Document.DomDocument;  
            WebBrowser wb = new WebBrowser();
            HTMLDocumentClass cls = (HTMLDocumentClass)wb.Document.DomDocument;

轉換以後用得到的HTMLDocumentClass就可操作所有屬性了。


轉自:http://blog.csdn.net/wsxqaz/article/details/7326502

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章