How can I get HTML source code from TWebBrowser

♀尐吖头ヾ 提交于 2019-11-29 06:34:35

You can use the IPersistStreamInit Interface and the save method to store the content of the Webbrowser in a Stream.

Uses 
  ActiveX;

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;

That works well too:

function GetHTML(w: TWebBrowser): String;
Var
  e: IHTMLElement;
begin
  Result := '';
  if Assigned(w.Document) then
  begin
     e := (w.Document as IHTMLDocument2).body;

     while e.parentElement <> nil do
     begin
       e := e.parentElement;
     end;

     Result := e.outerHTML;
  end;
end;

This has been asked and answered many times in the Embarcadero forums, with plenty of code examples posted. Search the archives.

The gist of it is that you Navigate() to the desired URL and wait for the OnDocumentComplete event to fire, then QueryInterface() the Document property for the IPersistStreamInit interface and call its save() method. Create a TStream object instance, such as a TMemoryStream, wrap it in a TStreamAdapter object, and then pass the adapter to save(). You can then load the TStream into the TMemo as needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!