Delphi TWebBrowser[11] 读写html代码

Delphi TWebBrowser[11] 读写html代码

注意:html 是UTF-8编码的在中文环境下需要转换成GB2312,否则会显示中文乱码

uses ActiveX;

function WB_ReadHTML(aBrowser: TWebBrowser): String;
begin
  Result := aBrowser.OleObject.Document.documentElement.outerHTML;
end;

procedure WB_WriteHTML(aBrowser: TWebBrowser; HTMLCode: string);
var
    sl: TStringList;
    ms: TMemoryStream;
begin
    if Assigned(aBrowser.Document) then
    begin
      sl := TStringList.Create;
      try
        ms := TMemoryStream.Create;
        try
          sl.Text := StringReplace(HTMLCode, 'UTF-8', 'GB2312', [rfReplaceAll, rfIgnoreCase]);
          sl.SaveToStream(ms);
          ms.Seek(0, 0);
          (aBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms));
        finally
          ms.Free;
        end;
      finally
        sl.Free;
      end;
    end;
end;

Delphi 调用:

procedure TForm1.Button1Click(Sender: TObject);
begin
  WB_WriteHtml(Webbrowser1, Memo1.Text);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Memo1.Text := WB_ReadHTML(Webbrowser1);
end;

  

 

创建时间:2020.11.23  更新时间:

  

posted on 2020-11-23 10:07  滔Roy  阅读(365)  评论(0编辑  收藏  举报

导航