A-A+
获取WebBrowser控件中的网页内容
HtmlDocument:提供对 WebBrowser 控件承载的 HTML 文档的顶级编程访问。属于命名空间System.Windows.Forms。在 System.Windows.Forms.dll中。
HtmlElement:表示网页内的一个 HTML 元素。属于命名空间System.Windows.Forms。在 System.Windows.Forms.dll中。
获取WebBrowser中的网页:
- HtmlDocument htmlDocument = this.webBrowser1.Document;
通过元素ID获取HTML元素:
- HtmlElement htmlElement = this.webBrowser1.Document.GetElementById(strElementID) ;
获取某一HTML元素的的样式名称:
- //GetAttribute() - 检索元素中已命名属性的值。
- htmlElement.GetAttribute("className")
获取指定HTML标记表示的元素集合:
- //获取网页中所有链接标签
- htmlDocument.GetElementsByTagName("a")
- //获取某个元素下的所有链接标签
- htmlDocument.GetElementsByTagName("a")
关于文档对象模型(DOM):可以通过HtmlDocument.DomDocument获取此HtmlDocument的非托管接口指针;通过HtmlElement.DomElement获取此元素的非托管接口指针。这样可以访问基础 COM 接口中的未公开属性或方法,为了使用非托管接口,需要将 MSHTML 库 (mshtml.dll) 导入到应用程序中。如何引用见下图:
示例代码如下:
- if (webBrowser1.Document != null)
- {
- mshtml.IHTMLDocument2 document = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
- mshtml.IHTMLElement element = document.body;
- }