下載
簡介
對於頁面下載的每個附件,都會發出 Page.Download 事件。所有這些附件都會下載到暫存資料夾中。您可以使用事件中的 Download 物件,取得下載網址、檔案名稱和酬載串流。
您可以使用 BrowserType.LaunchAsync() 中的 DownloadsPath 選項,指定要將下載的檔案儲存到何處。
注意
當產生下載檔案的瀏覽器 context 關閉時,下載的檔案將會被刪除。
以下是處理檔案下載最簡單的方式
// Start the task of waiting for the download before clicking
var waitForDownloadTask = page.WaitForDownloadAsync();
await page.GetByText("Download file").ClickAsync();
var download = await waitForDownloadTask;
// Wait for the download process to complete and save the downloaded file somewhere
await download.SaveAsAsync("/path/to/save/at/" + download.SuggestedFilename);
變化
如果您不知道是什麼啟動了下載,您仍然可以處理該事件
page.Download += (sender, download) => Console.WriteLine(download.Url);
請注意,處理事件會使控制流程分支,並使腳本更難以追蹤。您的情境可能會在您下載檔案時結束,因為您的主要控制流程並未等待此操作完成。
注意
如需上傳檔案,請參閱上傳檔案章節。