首先我们要认识到TWebBrowser其实是Delphi对Internet Explorer Browser的封装,也就是说它是一个ActiveX控件,看过TWebBrowser代码的朋友会发现这个空间的所有方法的实现部分都调用了DefaultInterface的方法,而TWebBrowser的这个属性是一个IWebBrowser2接口类型的对象,这个接口就是IE的接口。我们在使用TWebBrowser代替IE浏览器的目的大部分是为了能够让程序处理页面,实现自动对WebApplication的请求,所以我们首先想得到的就是TWebBrowser所浏览的内容。TWebBrowser的Documnet属性正是这一内容,Document其实是一个IHTMLDocument2,但是它被声明为IDispatch接口类型,我们需要把它转化为IHTMLDocument2类型然后是用我们需要的各种方法。在这里需要注意IHTMLDocument2是在MSHTML单元定义的,需要我们手动将这一单元加入到uses部分。具体代码如下:
var D : IHTMLDocument2;
begin
D := WebBrowser1.Document as IHTMLDocument2;
end;
begin
with WebBrowser1 do begin
D := Document as IHTMLDocument2;
Form := D.Forms.item('login_form',0) as IHTMLFormElement;
(form.item('login',0) as IHTMLElement).setAttribute('value',edit1.Text,0);
(form.item('passwd',0) as IHTMLElement).setAttribute('value',edit2.Text,0);
//form.submit; // this line work too
(form.item('.save',0) as IHTMLElement).click;
end;
end;
在这个时候我遇到了一个问题,就是在我要处理的页面中有两个Form,而且这样两个Form都没有名字,也就是说Form := D.Forms.item('login_form',0) as IHTMLFormElement;这一句中item的第一个参数的我们无法从网页中得到,同时在设置这个参数时我发现了一个问题,就是说如果在页面中有两个Form元素的话,第一个Form元素可以通过item(varEmpty,0)得到,第二个Form元素可以通过item(verNull,0)得到,而item的第二个参数完全不起作
这是我自己做的一个jsp程序):
var form : IHTMLFormElement ;
d:IHTMLDocument2 ;
begin
with WebBrowser1 do begin
d := document as IHTMLDocument2;
form := d.forms.item(varNull,01) as IHTMLFormElement;
(form.item('firstName',0) as IHTMLElement).setAttribute('value',edit1.Text,0);
(form.item('lastName',0) as IHTMLElement).setAttribute('value',edit1.Text,0);
form.submit;
end;
end;
var Links : IHTMLElementCollection;
D:IHTMLDocument2 ;
Element : IHTMLElement;
begin
with WebBrowser1 do begin
D := Document as IHTMLDocument2;
Links := D.links;
Element := (Links.Item(varempty,0) as IHTMLElement);
ShowMessage(Element.getAttribute('href',0));
Element := (Links.Item(varNull,0) as IHTMLElement);
ShowMessage(Element.getAttribute('href',0));
end;
end;