【发布时间】:2023-03-10 02:38:01
【问题描述】:
在我的应用程序中,我想将网站中的所有文本复制到一个字符串变量中。由于 Indy 的一些问题,我想使用 webbrowser 组件。
以下代码非常适合我:
procedure TForm1.Button1Click(Sender: TObject);
begin
WebBrowser1.Navigate('www.tribalwars.nl');
while WebBrowser1.Busy do
Application.ProcessMessages;
Memo1.Lines.Add((WebBrowser1.Document as IHTMLDocument2).body.innerText);
end;
但是,在上面的示例中,我使用了在 Form1 上手动创建的 WebBrowser。 现在我想在运行时创建它。我尝试了以下代码:
procedure TForm1.Button2Click(Sender: TObject);
var Web: TWebBrowser;
begin
Web := TWebBrowser.Create(nil);
Web.Navigate('www.tribalwars.nl');
while Web.Busy do
Application.ProcessMessages;
Memo1.Lines.Add((Web.Document as IHTMLDocument2).body.innerText); //This line raises the error mentioned below
Web.Free;
end;
不幸的是,它不断引发以下错误:
Project Project1.exe 引发异常类 $C0000005,并带有消息“0x005d9b4f 处的访问冲突:读取地址 0x00000000”。
我想我正在尝试使用尚未创建的东西,或者在那个方向的某个地方。 我希望有人能帮我解决这个问题!
编辑:whosrdaddy 提到我应该让这个组件可见。我怎样才能做到这一点?我试过这个,但它不起作用:
procedure TForm1.Button2Click(Sender: TObject);
var Web: TWebBrowser;
begin
Web := TWebBrowser.Create(nil);
Web.Left := 50;
Web.Top := 50;
Web.Width := 50;
Web.Height := 50;
Web.Visible := True;
Application.ProcessMessages;
Web.Navigate('www.tribalwars.nl');
while Web.Busy do
Application.ProcessMessages;
Memo1.Lines.Add((Web.Document as IHTMLDocument2).body.innerText);
Web.Free;
end;
【问题讨论】:
-
组件必须是可见的(即所有者表单),否则它不会呈现页面,因此 Document 将为 nil。将浏览器放在一个不可见的窗体上...
-
@whosrdaddy:我怎样才能让它可见? (见编辑开始帖子)
-
只需在设计模式下使用浏览器创建第二个表单并将表单可见属性设置为 false,然后在运行时创建该表单...
-
事后看来,我现在看到了您的问题,您的浏览器缺少父级。只需添加 TWinControl(Web).Parent := Self; .Create 之后将解决您的问题...
标签: delphi twebbrowser