大家可能經常會需要分析一段Html代碼,有的人可能會用WebBrowser,這個方法不錯,其實微軟還提供了另一個組件,mshtml(引用Microsoft.mshtml,這個可能有好幾個大家記得引用Framework目錄下的那個),這個東西提供分析html代碼的方法,而且用起來非常的方便。
- HTMLDocumentClass doc = new HTMLDocumentClass();
- IHTMLDocument2 doc2 = doc;
- doc2.write(html); //html就是外面傳進來的html代碼
HTMLDocumentClass doc = new HTMLDocumentClass();
IHTMLDocument2 doc2 = doc;
doc2.write(html); //html就是外面傳進來的html代碼
使用的時候只需要遞歸doc對象childNodes即可
- 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)
- {
- }
- }
- }
- }
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
- WebBrowser wb = new WebBrowser();
- 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