下载
Download对象由页面通过page.on("download")事件分发。
当浏览器上下文关闭时,所有属于该浏览器上下文的下载文件都会被删除。
下载事件会在下载开始时触发。下载路径将在下载完成后可用。
- Sync
- 异步
# Start waiting for the download
with page.expect_download() as download_info:
# Perform the action that initiates download
page.get_by_text("Download file").click()
download = download_info.value
# Wait for the download process to complete and save the downloaded file somewhere
download.save_as("/path/to/save/at/" + download.suggested_filename)
# Start waiting for the download
async with page.expect_download() as download_info:
# Perform the action that initiates download
await page.get_by_text("Download file").click()
download = await download_info.value
# Wait for the download process to complete and save the downloaded file somewhere
await download.save_as("/path/to/save/at/" + download.suggested_filename)
方法
取消
Added in: v1.13取消下载。如果下载已完成或已取消,操作不会失败。成功取消后,download.failure()
将解析为'canceled'
。
用法
download.cancel()
返回
删除
Added before v1.9删除已下载的文件。如有必要,将等待下载完成。
用法
download.delete()
返回
失败
Added before v1.9如果有下载错误则返回错误信息。必要时会等待下载完成。
用法
download.failure()
返回
路径
Added before v1.9对于成功的下载,返回下载文件的路径;对于失败/取消的下载则抛出异常。该方法会在必要时等待下载完成。当远程连接时会抛出异常。
请注意下载的文件名是一个随机GUID,使用download.suggested_filename来获取建议的文件名。
用法
download.path()
返回
save_as
Added before v1.9将下载内容复制到用户指定的路径。在下载仍在进行时调用此方法是安全的。如有必要,将等待下载完成。
用法
- Sync
- 异步
download.save_as("/path/to/save/at/" + download.suggested_filename)
await download.save_as("/path/to/save/at/" + download.suggested_filename)
参数
-
path
Union[str, pathlib.Path]#下载文件应该被复制到的路径。
返回
属性
页面
Added in: v1.12获取下载所属的页面。
用法
download.page
返回
建议的文件名
Added before v1.9返回此下载的建议文件名。通常由浏览器根据Content-Disposition
响应头或download
属性计算得出。详情请参阅whatwg规范。不同浏览器可能采用不同的计算逻辑。
用法
download.suggested_filename
返回
网址
Added before v1.9返回下载的URL。
用法
download.url
返回