如何在以编程方式单击下载按钮后下载文件,因此无需知道下载文件的URL.
下载文件后,出现提示并询问您是否要保存文件,按"是"后,另一个提示会询问您要保存文件的位置.因此,首先下载文件,可能在某个地方的缓冲区中,在初始下载后,会出现提示.
因此,一旦单击按钮,您如何捕获下载流并将其保存为某个文件,而不显示弹出提示?
(任何单击按钮的方法都可以,以下情况应该没问题.)
procedure TForm1.Button1Click(Sender: TObject);
var
x: integer;
ovLinks: OleVariant;
begin
WebBrowser1.Navigate('The web page');
//wait for page to down load
ovLinks := WebBrowser1.OleObject.Document.all.tags('A');
if ovLinks.Length > 0 then
begin
for x := 0 to ovLinks.Length-1 do
begin
if Pos('id of button', ovLinks.Item(x).id) > 0 then
//or if Pos('href of button', ovLinks.Item(x).href) > 0 then
begin
ovLinks.Item(x).click;
Break;
end;
end;
end;
end;
Run Code Online (Sandbox Code Playgroud)
这个问题的原因是:无法始终找到文件的URL.例如:在这个网站上,我无法以编程方式找到网址,但在按下导出按钮后,使用IE,文件被下载到"Temporary Internet Files"文件夹中.在IE'Temporary Internet Files'文件夹中,它有一个列'Internet地址',显示网址.但是在Chrome中没有这样的数据.但是,在这个网站上,我可以以编程方式找到网址,但是当我下载文件时,按"此处",该文件不会出现在IE"Temporary Internet Files"文件夹中.对于其他网站,可以在文件夹中找到网址并通过编程方式找到它,但在其他网站上无法找到网址.
IDownloadManager使用其Download方法将界面实现到Web浏览器控件,您可以简单地控制所需内容.Download每当您要下载文件时(仅当弹出另存为对话框时)才会调用该方法.
1.嵌入式Web浏览器
您可以使用Embedded Web Browser已实现此接口的控件,该控件将触发OnFileDownload与同一命名事件不同的控件TWebBrowser.例如this thread,请参阅如何使用它.
2.自己动手吧
另一个选择是您可以TWebBrowser自己实现它.在下面的例子中,我使用插入类只是为了显示原理,但是很容易将它包装成一个组件(这就是我OnBeforeFileDownload发布的原因).
2.1.OnBeforeFileDownload事件
TWebBrowser在这个插入的类中唯一的扩展是在OnBeforeFileDownload下载文件时触发的事件(在保存为弹出对话框之前,而不是OnFileDownload事件,而不是在下载文档本身时).如果您不为其编写事件处理程序,则Web浏览器控件将像以前一样运行(显示另存为对话框).如果编写事件处理程序并将False返回到其Allowed声明的参数,则将取消文件保存.如果将True返回到Allowed参数(默认情况下是什么),将显示另存为对话框.请注意,如果您通过设置Allowed为False 取消下载,则需要自己下载文件(因为我在此示例中使用Indy同步).为了这个目的,有FileSource常量参数,包含下载的文件URL.以下是事件参数概述:
2.2.IDownloadManager实现
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
StdCtrls, OleServer, OleCtrls, Dialogs, ActiveX, MSHTML, UrlMon, SHDocVw,
IdHTTP;
const
IID_IDownloadManager: TGUID = '{988934A4-064B-11D3-BB80-00104B35E7F9}';
SID_SDownloadManager: TGUID = '{988934A4-064B-11D3-BB80-00104B35E7F9}';
type
IDownloadManager = interface(IUnknown)
['{988934A4-064B-11D3-BB80-00104B35E7F9}']
function Download(pmk: IMoniker; pbc: IBindCtx; dwBindVerb: DWORD;
grfBINDF: DWORD; pBindInfo: PBindInfo; pszHeaders: PWideChar;
pszRedir: PWideChar; uiCP: UINT): HRESULT; stdcall;
end;
TBeforeFileDownloadEvent = procedure(Sender: TObject; const FileSource: WideString;
var Allowed: Boolean) of object;
TWebBrowser = class(SHDocVw.TWebBrowser, IServiceProvider, IDownloadManager)
private
FFileSource: WideString;
FOnBeforeFileDownload: TBeforeFileDownloadEvent;
function QueryService(const rsid, iid: TGUID; out Obj): HRESULT; stdcall;
function Download(pmk: IMoniker; pbc: IBindCtx; dwBindVerb: DWORD;
grfBINDF: DWORD; pBindInfo: PBindInfo; pszHeaders: PWideChar;
pszRedir: PWideChar; uiCP: UINT): HRESULT; stdcall;
protected
procedure InvokeEvent(ADispID: TDispID; var AParams: TDispParams); override;
published
property OnBeforeFileDownload: TBeforeFileDownloadEvent read FOnBeforeFileDownload write FOnBeforeFileDownload;
end;
type
TForm1 = class(TForm)
Button1: TButton;
WebBrowser1: TWebBrowser;
FileSourceLabel: TLabel;
FileSourceEdit: TEdit;
ShowDialogCheckBox: TCheckBox;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure BeforeFileDownload(Sender: TObject; const FileSource: WideString;
var Allowed: Boolean);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TWebBrowser }
function TWebBrowser.Download(pmk: IMoniker; pbc: IBindCtx; dwBindVerb,
grfBINDF: DWORD; pBindInfo: PBindInfo; pszHeaders, pszRedir: PWideChar;
uiCP: UINT): HRESULT;
var
Allowed: Boolean;
begin
Result := E_NOTIMPL;
if Assigned(FOnBeforeFileDownload) then
begin
Allowed := True;
if pszRedir <> '' then
FFileSource := pszRedir;
FOnBeforeFileDownload(Self, FFileSource, Allowed);
if not Allowed then
Result := S_OK;
end;
end;
procedure TWebBrowser.InvokeEvent(ADispID: TDispID; var AParams: TDispParams);
begin
inherited;
// DispID 250 is the BeforeNavigate2 dispinterface and to the FFileSource here
// is stored the URL parameter (for cases, when the IDownloadManager::Download
// won't redirect the URL and pass empty string to the pszRedir)
if ADispID = 250 then
FFileSource := OleVariant(AParams.rgvarg^[5]);
end;
function TWebBrowser.QueryService(const rsid, iid: TGUID; out Obj): HRESULT;
begin
Result := E_NOINTERFACE;
Pointer(Obj) := nil;
if Assigned(FOnBeforeFileDownload) and IsEqualCLSID(rsid, SID_SDownloadManager) and
IsEqualIID(iid, IID_IDownloadManager) then
begin
if Succeeded(QueryInterface(IID_IDownloadManager, Obj)) and
Assigned(Pointer(Obj))
then
Result := S_OK;
end;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
HTMLWindow: IHTMLWindow2;
HTMLDocument: IHTMLDocument2;
begin
WebBrowser1.Navigate('http://financials.morningstar.com/income-statement/is.html?t=AAPL&ops=clear');
while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do
Application.ProcessMessages;
HTMLDocument := WebBrowser1.Document as IHTMLDocument2;
if not Assigned(HTMLDocument) then
Exit;
HTMLWindow := HTMLDocument.parentWindow;
if Assigned(HTMLWindow) then
try
HTMLWindow.execScript('SRT_stocFund.Export()', 'JavaScript');
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ReportMemoryLeaksOnShutdown := True;
WebBrowser1.OnBeforeFileDownload := BeforeFileDownload;
end;
procedure TForm1.BeforeFileDownload(Sender: TObject; const FileSource: WideString;
var Allowed: Boolean);
var
IdHTTP: TIdHTTP;
FileTarget: string;
FileStream: TMemoryStream;
begin
FileSourceEdit.Text := FileSource;
Allowed := ShowDialogCheckBox.Checked;
if not Allowed then
try
IdHTTP := TIdHTTP.Create(nil);
try
FileStream := TMemoryStream.Create;
try
IdHTTP.HandleRedirects := True;
IdHTTP.Get(FileSource, FileStream);
FileTarget := IdHTTP.URL.Document;
if FileTarget = '' then
FileTarget := 'File';
FileTarget := ExtractFilePath(ParamStr(0)) + FileTarget;
FileStream.SaveToFile(FileTarget);
finally
FileStream.Free;
end;
finally
IdHTTP.Free;
end;
ShowMessage('Downloading finished! File has been saved as:' + sLineBreak +
FileTarget);
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
end.
Run Code Online (Sandbox Code Playgroud)
2.3.IDownloadManager项目
您可以将上面的代码(在Delphi 2009中编写)作为一个完整的项目下载from here.