编辑 将其缩小到这一行,
HTML := wb.OleObject.Document.documentElement.innerHTML;
这会消耗时间......如何才能加快速度?
使用以下代码,我的应用程序在尝试访问页面的 HTML (Delphi XE) 时可能会挂起 1-2 秒。
function Button1Click(Sender : TObject);
begin
wb.navigate('http://10.0.0.154/stats');
// Use a timer to poll the page - dont wait and process app messages
timer1.enabled := true;
end;
procedure Timer1Timer(Sender : TObject);
var
HTML : WideString;
begin
If GetHTML(HTML) = true then
begin
Timer1.enabled := false;
{ do something }
end;
end;
function GetHTML(var HTML : WideString) : boolean;
var
Document : IHTMLDocument2;
begin
HTML := '';
Result := false;
Document := wb.DOcument as IHTMLDocument2;
If Assigned(Document) then
begin
try
HTML := wb.OleObject.Document.documentElement.innerHTML;
Result := true;
except
Result := false;
end;
end;
end;
但是我注意到在我的 GetHTML 方法中可能需要 1-2 秒才能返回某些内容,并且它会锁定 UI。使用 Delphi XE 查看 AQTime,它表示方法调用很慢(1-2 秒)。它是零星的,我想知道当页面仍在加载中时它是否会失败。
我正在加载的页面是一个内部页面,充满了 javascript 和 500k 大,我无法使用 OnDocumentComplete 因为它在页面准备好之前触发,即使我检查 ReadyState 它仍然会触发早。
任何人都可以提供一些线索,如果他们有一种更快的方式我可以访问 TWebbrowser 的 HTML?
最佳答案
请记住,导航页面时 OnDocumentComplete 可以触发多次(帧)。
如何正确实现OnDocumentComplete:
procedure YourForm.OnDocumentComplete(
Sender: TObject;
const pDisp: IDispatch;
var URL: OleVariant);
var
currentBrowser: IWebBrowser;
topBrowser: IWebBrowser;
document: OleVariant;
windowName: string;
begin
currentBrowser := pDisp as IWebBrowser;
topBrowser := (Sender as TWebBrowser).DefaultInterface;
if currentBrowser = topBrowser then
ShowMessage('Complete document was loaded')
else
begin
document := currentBrowser.Document;
windowName := document.ParentWindow.Name;
ShowMessage(Format('Frame "%s" was loaded', [windowName]));
end;
end;
来源:
http://www.cryer.co.uk/brian/delphi/twebbrowser/twebbrowser_events.htm#OnDocumentComplete
关于delphi - 尝试访问 TWebbrowsers HTML 时应用程序锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930725/