WebBrowser 操作页面中的元素

来源:互联网 发布:沈阳盘古网络招聘 编辑:程序博客网 时间:2024/05/01 23:50
可以通过引入 mshtml 中的一些类可以实现操作页面中的元素。
项目引用“C:/WINDOWS/system32/mshtml.tlb”。

mshtml.IHTMLDocument2 iHTMLDocument2 = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
mshtml.IHTMLWindow2 iHTMLWindow2 = (mshtml.IHTMLWindow2)iHTMLDocument2.parentWindow;

// 根据 name 查找页面中的元素。根据类型不同,转成相应的类型。
// 找页面中的 Frame 元素。
mshtml.IHTMLFrameBase2 iFrame = (mshtml.IHTMLFrameBase2)iHTMLDocument2.all.item("FrameName", 0);
mshtml.IHTMLDocument2 iHTMLDocument2 = iFrame.contentWindow.document;



// 找页面中的 Input 元素。
mshtml.IHTMLInputElement input = (mshtml.IHTMLInputElement)iHTMLDocument2.all.item("InputName", 0);

// 找页面中的 Img 元素。
mshtml.IHTMLImgElement img1 = (mshtml.IHTMLImgElement)iHTMLDocument2.all.item("img1", 0);
操作如:img1.src、img1.alt、img1.height + img1.align

mshtml名字空间里对 Html 的每一个元素都有对应的一个类。这个类就可以设置或读取元素的属性。
HTMLDivElement、HTMLSpanElement、HTMLAnchorElement 等等。

// 实现单击按钮
mshtml.IHTMLElement iHTMLElement = (mshtml.IHTMLElement)iHTMLDocument2.all.item(name, 0);
iHTMLElement.click();// 单击
原创粉丝点击