[英]How can I get HTML source code from TWebBrowser
How can I get source code from WebBrowser component?如何从 WebBrowser 组件获取源代码?
I want to get source code of active page on WebBrowser component and write it to a Memo component.我想获取 WebBrowser 组件上活动页面的源代码并将其写入 Memo 组件。
Thanks.谢谢。
You can use the IPersistStreamInit
Interface and the save method to store the content of the Webbrowser in a Stream.您可以使用
IPersistStreamInit
接口和save方法将 Webbrowser 的内容存储在 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:这也很管用:
uses MSHTML;
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.这已在 Embarcadero 论坛中被多次询问和回答,并发布了大量代码示例。 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.它的要点是您
Navigate()
到所需的 URL 并等待OnDocumentComplete
事件触发,然后QueryInterface()
IPersistStreamInit
接口的Document
属性并调用其save()
方法。 Create a TStream
object instance, such as a TMemoryStream
, wrap it in a TStreamAdapter
object, and then pass the adapter to save()
.创建一个
TStream
object 实例,例如TMemoryStream
,将其包装在TStreamAdapter
object 中,然后将适配器传递给save()
。 You can then load the TStream
into the TMemo
as needed.然后,您可以根据需要将
TStream
加载到TMemo
中。
Why not Quick and Dirty:为什么不快速而肮脏:
OnNavigateComplete2()
Form1.RichEdit1.Text:=(WebBrowser1.OleObject.Document.documentElement.outerhtml);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.