读书人

控制台中动态创建Webbrowser后获取源码

发布时间: 2012-03-17 19:06:27 作者: rapoo

控制台中动态创建Webbrowser后获取源码

Delphi(Pascal) code
program Project1;{$APPTYPE CONSOLE}uses  SysUtils,SHDocVw,MSHTML;var  iall : IHTMLElement;  Webbrowser:TWebBrowser;begin  WebBrowser :=TWebBrowser.Create(nil);  WebBrowser.Navigate('http://192.168.1.101/1.html');  Sleep(1000);  if Assigned(WebBrowser.Document) then  begin    iall := (WebBrowser.Document AS IHTMLDocument2).body;    while iall.parentElement <> nil do    begin      iall := iall.parentElement;    end;    Writeln(iall.outerHTML);  end;  Readln;  Webbrowser.Free;end.


1.html里存放的是文本 "success=true"

使用上边的代码无法正确输出success=true这一串字符

而在VCL Forms Application 中则可以,请问是哪的原因?

如何解决呢?

[解决办法]
If all you want is return result of some URL why do you need to embed whole webbrowser? if you just need the result then try Indy.

retStr := IdHTTP.Get('http://192.168.1.101/1.html');

Hope it helps.

//Ali
[解决办法]
IdHTTP.Get will also return you whole HTML or 源码 of that link.

Do you want to display the results as HTML Browser??

//Ali
[解决办法]
Now your requirements are clear. Use below code to retrieve HTML via webbrowser.

Delphi(Pascal) code
procedure Pause(const ADelay: Cardinal);var   Start: Cardinal;begin    Start := Windows.GetTickCount;    repeat          Application.ProcessMessages;    until Int64(Windows.GetTickCount) - Int64(Start) >= ADelay;end;function getHTML(WB : TWebBrowser) : String ; var   PersistStream: IPersistStreamInit;   Stream: IStream;   strStream: TStringStream; begin   Result := '';   if Assigned(WB.Document) then   begin   PersistStream := WB.Document as IPersistStreamInit;   strStream := TStringStream.Create('') ;   try     Stream := TStreamAdapter.Create(strStream, soReference) as IStream;     if Succeeded(PersistStream.Save(Stream, True)) then         Result := strStream.DataString;   finally     strStream.Free;   end;   end;end;procedure TForm1.Button1Click(Sender: TObject);var   browser : TWebBrowser;   Flags : OleVariant;begin     Flags := navNoHistory or navNoReadFromCache or navNoWriteToCache;     browser := TWebBrowser.Create(nil);     try       browser.Navigate(Edit1.Text,  Flags);       while browser.Busy do         Pause(5);       memo1.Text := getHTML(browser);     finally           browser.Free;     end;end;
[解决办法]
Definitely you can not have any TWinControl descendent in console environment. And plus I don't understand why would you go with WinControl in non-window (console) environment?

//Ali

读书人网 >.NET

热点推荐