MSHTML是微軟公司的一個COM組件,該組件封裝了HTML語言中的所有元素及其屬性,通過其提供的標準接口,可以訪問指定網頁的所有元素.
MSHTML對象模型是由一些對象和集合組成的.處於根部的是HTML,描述了打開頁面的1個窗口,包括一系列集合和對象。如Frames集合,History,Location,Navigator,Document,Vi—sum,Event對象等.其中描述呈現在客戶窗口實際網頁的是Document對象。由一系列的屬性、方法、對象和集合組成.其中All集合中包含網頁中所有標記(Tag)元素,其主要的方法和屬性有:
(1)Length(長度):即標記出現的個數,可以把標記的集合理解爲從0開始的一維數組,其次序按照標記在網頁位置排列;
(2)Tags(標記):用於過濾出給定標記的集合,如Doc.Al1.Tags(P)得到所有分段標記P;
(3)Item(項目):用於選擇集合中的某1個元素,如object.item(0)得到集合的第1個元素,而object.item(i)得到第i+1個元素.
此外,IHTMLElement也是個常用的集合對象,代表網頁中指定標記的集合,通過這個集合對象,可以得到網頁上特定標記的內容.IHTMLElement有4個主要屬性:
(1)InnerText:開始標記和結束標記之間的文本;
(2)InnerHTML:開始標記和結束標記之間的文本和HTML;
(3)OuterText:對象的文本;
(4)OuterHTML:對象的文本和HTML.
注意:使用前加入單元mshtml
演示表單提交
procedure TForm1.Button1Click(Sender: TObject);
var
Doc:IHTMLDocument2;
input:OleVariant;
userinputelement,pwdinputelement:ihtmlinputelement;
begin
doc:=webbrowser1.document as ihtmldocument2;
userinputelement:=(doc.all.item('user'(也就是網頁中用戶名控件的名字),0) as ihtmlinputelement);
userinputelement.value:=edit1.text;(也就是你要向網頁輸入的東西)
pwdinputelement:=(doc.all.item('password',0) as ihtmlinputelement);
pwdinputelement.value:=edit2.text;
input:=doc.all.item('submit',0);
input.click;
end;
當提交數據按鈕沒有NAME屬性時,採用如下方法:
procedure TForm1.Button1Click(Sender: TObject);
var
Doc:IHTMLDocument2;
form:ithmlformelement;
userinputelement,pwdinputelement:ihtmlinputelement;
begin
doc:=webbrowser1.document as ihtmldocument2;
userinputelement:=(doc.all.item('user'(也就是網頁中用戶名控件的名字),0) as ihtmlinputelement);
userinputelement.value:=edit1.text;(也就是你要向網頁輸入的東西)
pwdinputelement:=(doc.all.item('password',0) as ihtmlinputelement);
pwdinputelement:=edit2.text;
form:=(doc.all.item('login_form',0) as ihtmlformelement):
form.submit;
end;
登錄'按鈕一般都是網頁中默認的回車按鈕,所以可以用上面代碼來代替前面的點擊按鈕
讀取某網頁內容
在創建窗體的時候打開一網頁
webbrowser1.navigate('http://www.baidu.com')
procedure TForm1.Button1Click(Sender: TObject);
begin
memo1.lines.add(ihtmldocument2(webbrowser1.document).body.outerhtml);
end;
這樣一來memo1中顯示www.baidu.com的html
利用webbrowser1控件瀏覽某txt中文件的內容,並以html形式來顯示出來
在webbrowser1的控件中的ondocumentcomplete事件加入如下代碼
procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
webdoc:htmldocument ;
webbody:htmlbody;
begin
webdoc:=webbrowser1.document as htmldocument;
webbody:=webdoc.body as htmlbody;
webbody.insertAdjacentHTML('beforeend','<form method='POST' action=''>');
webbody.insertAdjacentHTML('beforeend','Password: ');
webbody.insertAdjacentHTML('beforeend','<input type='password' >');
webbody.insertAdjacentHTML('beforeend','<input type='submit' value='LOGIN' >');
webbody.insertAdjacentHTML('beforeend',' ');
webbody.insertAdjacentHTML('beforeend','</form>');
end;