用HTMLDocumentClass分析Html代码(以及读取HtmlElement所有属性方法)

大家可能经常会需要分析一段Html代码,有的人可能会用WebBrowser,这个方法不错,其实微软还提供了另一个组件,mshtml(引用Microsoft.mshtml,这个可能有好几个大家记得引用Framework目录下的那个),这个东西提供分析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)
                        {
                            
                        }
                    }
                }
            }

顺便说一下,IHTMLDOMNode对象其实是所有节点(包括关闭节点比如"</a>"这个也算一个IHTMLDOMNode)

所以大家判断是不是开头的节点只要判断一下是不是不等于HTMLUnknownElementClass

大家如果使用WebBrowser肯能一直有个困惑WebBrowser提供的HtmlElement对象没有提供Attribute属性集合,也就无法通过循环获得节点的所有属性,其实通过mshtml可以解决这个问题。大家可用DomDocument转换为HTMLDocumentClass

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

转换以后用得到的HTMLDocumentClass就可操作所有属性了。

你可能感兴趣的:(html,微软,WebBrowser)