下载
介绍
页面下载的每个附件,都会触发 page.on("download") 事件。所有这些附件都会下载到一个临时文件夹中。你可以使用事件中的 Download 对象获取下载 URL、文件名和有效载荷流。
你可以使用 downloads_path browser_type.launch() 中的选项来指定下载文件的保存位置。
注意
下载的文件在产生它们的浏览器上下文关闭时会被删除。
以下是处理文件下载的最简单方法
- 同步
- 异步
# 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)
变体
如果你不知道是什么触发了下载,你仍然可以处理该事件
- 同步
- 异步
page.on("download", lambda download: print(download.path()))
async def handle_download(download):
print(await download.path())
page.on("download", handle_download)
请注意,处理该事件会分叉控制流,使脚本更难跟踪。你的场景可能会在你下载文件时结束,因为你的主控制流并未等待此操作完成。
注意
关于文件上传,请参阅文件上传部分。