#说明: If your program does not pass, make sure you have added the following lines of code.
Initialization
OleInitialize (nil);
Finalization
OleUninitialize;
1. Save WebBrowser The current page or URL is a MHT file format.
Procedure saveasmht (const webbrowser:twebbrowser; const filename:string);
Needs ActiveX, Cdo_tlb, adodb_tlb, [Install type library CDO, and ActiveX HTML Oleobject.
Var
Imsg:imessage;
Iconf:iconfiguration;
Stream: _stream;
Begin
Imsg: = comessage.create;
iconf: = coconfiguration.create;
Try
Imsg. Configuration: = iconf;
Imsg. HTMLBody: = getbrowserhtml (WebBrowser);
Stream: = imsg. GetStream;
Stream. SaveToFile (FileName, adsavecreateoverwrite);
Finally
Imsg: = nil;
iconf: = nil;
Stream: = nil;
End
End
Procedure saveurlasmht (const url:string; const filename:string);
Needs ActiveX, Cdo_tlb, Adodb_tlb,
Var
Imsg:imessage;
Iconf:iconfiguration;
Stream: _stream;
Begin
Imsg: = comessage.create;
iconf: = coconfiguration.create;
Try
Imsg. Configuration: = iconf;
Imsg. Createmhtmlbody (Url,cdosuppressnone, ', ');
Imsg. Createmhtmlbody (Url,cdosuppressall, ', ');
Stream: = imsg. GetStream;
Stream. SaveToFile (FileName, adsavecreateoverwrite);
Finally
Imsg: = nil;
iconf: = nil;
Stream: = nil;
End
End
2. Three ways to directly load HTML code into webbrowser.
Procedure WBLoadHTML1 (Webbrowser:twebbrowser; htmlcode:string);
Var
Sl:tstringlist;
Ms:tmemorystream;
Begin
Webbrowser.navigate (' About:blank ');
While Webbrowser.readystate < readystate_interactive do
Application.processmessages;
If assigned (webbrowser.document) then
begin
SL: = Tstringlist.create;
Try
ms: = Tmemorystream.create
try
sl. Text: = Htmlcode;
sl. Savetostream (MS);
Ms. Seek (0, 0);
(webbrowser.document as IPersistStreamInit). Load (Tstreamadapter.create (ms));
finally
Ms. Free;
end;
finally
sl. Free;
end;
end;
End;
Procedure WBLoadHTML2 (Webbrowser:twebbrowser; htmlcode:string);
Begin
Webbrowser.navigate (' about: ' +htmlcode);
End
Procedure WBLoadHTML3 (Webbrowser:twebbrowser; htmlcode:string);
Var
Htmldocument:ihtmldocument2;
V:variant;
Begin
HTMLDocument: = webbrowser.document as IHTMLDocument2;
Webbrowser.navigate (' About:blank ');
While Webbrowser.readystate < readystate_interactive do
Application.processmessages;
if (Assigned (htmldocument)) Then
Begin
V: = Vararraycreate ([0, 0], varvariant);
V[0]: = Htmlcode; Here ' s your HTML string
Htmldocument.write (Psafearray (Tvardata (v)). Varray));
Htmldocument.close;
End
End
3. Get the WebBrowser HTML code
Function getbrowserhtml (const webbrowser:twebbrowser): String;
//needs ActiveX, Cdo_tlb, Adodb_tlb,
var
Strstream:tstringstream;
Adapter:istream;
Browserstream:ipersiststreaminit;
Begin
Strstream: = Tstringstream.create (');
Try
browserstream: = webbrowser.document as IPersistStreamInit;
Adapter: = Tstreamadapter.create (strstream,soreference);
Browserstream.save (adapter,true);
Result: = strstream.datastring;
finally
end;
Strstream.free ();
End;