我有三个函数来获取和设置HTML,第一个函数捕获HTML DOM,第二个函数捕获原始HTML页面,因为最后一个函数在TWebBrowser中注入一个新代码,但是按照我想要的方式和需要。
注入新代码后成功运行,但只能直观地看到,当我点击右键并可视化源代码打开记事本而不是DOM代码时,我会看到页面的代码。
有没有办法重写原始HTML?
获取HTML源代码(DOM)。
function GetHTML( WebBrowser : TWebBrowser ) : String;
var
HTMLElement : IHTMLElement;
begin
Result := '';
if Assigned( WebBrowser.Document ) then begin
HTMLElement := ( WebBrowser.Document as IHTMLDocument2 ).body;
if Assigned( HTMLElement ) then begin
while HTMLElement.parentElement <> nil do begin
HTMLElement := HTMLElement.parentElement;
end;
Result := HTMLElement.outerHTML;
end else begin
Result := ( WebBrowser.Document as IHTMLDocument2 ).all.toString;
end;
end;
end;
获取HTML源代码(“原始HTML”)。
function GetWebBrowserHTML( Const WebBrowser : TWebBrowser ) : String;
var
LStream : TStringStream;
Stream : IStream;
LPersistStreamInit : IPersistStreamInit;
begin
if not Assigned( WebBrowser.Document ) then exit;
LStream := TStringStream.Create( '' );
try
LPersistStreamInit := WebBrowser.Document as IPersistStreamInit;
Stream := TStreamAdapter.Create( LStream, soReference );
LPersistStreamInit.Save( Stream, true );
Result := LStream.DataString;
finally LStream.Free( );
end;
end;
重写HTML源代码(仅在视觉上明显)。
procedure WBAppendHTML( WB : SHDocVw.TWebbrowser;const HTML : string );
var
Doc : MSHTML.IHTMLDocument2;
BodyElem : MSHTML.IHTMLBodyElement;
Range : MSHTML.IHTMLTxtRange;
begin
if not SysUtils.Supports( WB.Document, MSHTML.IHTMLDocument2, Doc ) then begin
Exit;
end;
if not SysUtils.Supports( Doc.body, MSHTML.IHTMLBodyElement, BodyElem ) then
begin
Exit;
end;
Range := BodyElem.createTextRange;
Range.collapse( False );
Range.pasteHTML( HTML );
end;
答案 0 :(得分:1)
我知道的唯一方法是自己从网络服务器下载HTML并根据需要进行更改(包括在<base href
中插入<head>
&gt;标记,以便解析相关链接) ,然后通过其TWebBrowser
方法将更改的HTML加载到IPersisteStreamInit.load()
(如果尚未加载Document
,请将TWebBrowser
导航到"about:blank"
网址第一)。