Skip to main content

下载

介绍

¥Introduction

对于页面下载的每个附件,都会触发 page.on('download') 事件。所有这些附件都会下载到临时文件夹中。你可以使用事件中的 Download 对象获取下载 URL、文件名和负载流。

¥For every attachment downloaded by the page, page.on('download') event is emitted. All these attachments are downloaded into a temporary folder. You can obtain the download url, file name and payload stream using the Download object from the event.

你可以使用 browserType.launch() 中的 downloadsPath 选项指定保存下载文件的位置。

¥You can specify where to persist downloaded files using the downloadsPath option in browserType.launch().

注意

当生成这些文件的浏览器上下文关闭时,下载的文件将被删除。

¥Downloaded files are deleted when the browser context that produced them is closed.

这是处理文件下载的最简单方法:

¥Here is the simplest way to handle the file download:

// Start waiting for download before clicking. Note no await.
const downloadPromise = page.waitForEvent('download');
await page.getByText('Download file').click();
const download = await downloadPromise;

// Wait for the download process to complete and save the downloaded file somewhere.
await download.saveAs('/path/to/save/at/' + download.suggestedFilename());

变化

¥Variations

如果你不知道是什么启动了下载,你仍然可以处理该事件:

¥If you have no idea what initiates the download, you can still handle the event:

page.on('download', download => download.path().then(console.log));

请注意,处理事件会分叉控制流并使脚本更难以遵循。当你下载文件时,你的场景可能会结束,因为你的主控制流不等待此操作解决。

¥Note that handling the event forks the control flow and makes the script harder to follow. Your scenario might end while you are downloading a file since your main control flow is not awaiting for this operation to resolve.

注意

关于上传文件,请参阅 上传文件 部分。

¥For uploading files, see the uploading files section.