經常看到有人在論壇里問,如何將網頁內容保存為字符串以及根據字符串顯示成網頁。這里說說我的看法。
將網頁內容保存為字符串很簡單,只需(webbrowser1.Document as Ihtmldocument2).body.outerHtml一句就可得到網頁的html源碼,一個WideString型。如果考慮到要等ie下載完整個網頁后再保存為string可以這樣寫(在窗體中放置了一個memo控件以查看該頁面的html源碼)。
PRocedure tatonreg.readdocument;
var
  ipStream: IPersistStreamInit;
  MemoryStream: TMemoryStream;
begin
  ie為twebbrowser控件或為一個twebbrowser實例
  with ie do begin
    while (ReadyState <> READYSTATE_COMPLETE) and (not forms.application.Terminated) do
    Forms.Application.ProcessMessages;
    if Assigned(document) then begin
      MemoryStream := TMemoryStream.Create;
      try
      IpStream := document as IPersistStreamInit;
      if not Assigned(IpStream) then showmessage('錯誤') else
      if Succeeded(IpStream.save(TStreamadapter.Create(A), TRUE))
        then begin
          MemoryStream.Seek(0, 0);
          memo1.lines.LoadFromStream(A);
        end;
      except
      end;
      MemoryStream.Free;
    end;
  end;
end;
程序運行后memo1.text就是該網頁的源碼了。
twebbrowser控件不能直接根據字符串顯示成網頁,必須先把string轉成stream。
procedure tatonreg.loaddocument;
var
m:tmemorystream;
begin
  M := TMemoryStream.Create;
  memo1.Lines.SaveToStream(M);
  M.seek(0, 0);
  if not Assigned(ie.document) then begin
    ie.navigate('about:blank');
    while ie.readystate <> READYSTATE_COMPLETE do Forms.Application.ProcessMessages;
  end;
  (ie.Document as IPersistStreamInit).Load(TStreamadapter.Create(M));
end;
我做了一個這類的軟件,可到我的個人主頁上下載http://aton.126.com
這段時間我對ie編程產生了濃厚的興趣。大有不精通這類編程誓不罷休之勢。歡迎感興趣著與我共同探討。
新聞熱點
疑難解答