下載
簡介
每個頁面下載的附件都會觸發 page.on("download")
事件。所有這些附件都會下載到一個臨時資料夾中。您可以使用事件中的 Download 物件獲取下載的 URL、檔案名稱和有效負載流。
您可以使用 downloads_path
選項來指定下載檔案的保存位置 browser_type.launch()
。
note
下載的檔案會在產生它們的瀏覽器情境關閉時被刪除。
以下是處理檔案下載的最簡單方法:
- Sync
- Async
# 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)
變體
如果您不知道是什麼啟動了下載,您仍然可以處理這個事件:
- 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
如需上傳檔案,請參閱上傳檔案部分。