下载
对于页面下载的每个附件,都会发出 page.on("download") 事件。所有这些附件都会下载到一个临时文件夹中。您可以使用事件中的 Download 对象获取下载 URL、文件系统路径和有效负载流。
您可以使用 browser_type.launch(**kwargs) 中的 downloads_path 选项指定下载文件的持久化位置。
note
当生成下载文件的浏览器上下文关闭时,下载的文件将被删除。
这是处理文件下载的最简单方法:
- Sync
- Async
# Start waiting for the download
with page.expect_download() as download_info:
# Perform the action that initiates download
page.locator("button#delayed-download").click()
download = download_info.value
# Wait for the download process to complete
print(download.path())
# Save downloaded file somewhere
download.save_as("/path/to/save/download/at.txt")
# Start waiting for the download
async with page.expect_download() as download_info:
# Perform the action that initiates download
await page.locator("button#delayed-download").click()
download = await download_info.value
# Wait for the download process to complete
print(await download.path())
# Save downloaded file somewhere
download.save_as("/path/to/save/download/at.txt")
Variations
如果您不知道是什么启动了下载,您仍然可以处理该事件:
- Sync
- Async
page.on("download", lambda download: print(download.path()))
async def handle_download(download):
print(await download.path())
page.on("download", handle_download)
请注意,处理该事件会分叉控制流,使脚本更难理解。您的场景可能会在下载文件时结束,因为您的主控制流没有等待此操作解析。
note
有关上传文件,请参阅 上传文件 部分。