下載
簡介
對於頁面下載的每個附件,都會發出 page.on("download") 事件。所有這些附件都會下載到一個臨時資料夾中。您可以使用事件中的 Download 物件來取得下載網址、檔案名稱和 payload 串流。
您可以使用 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)
請注意,處理事件會fork控制流程,並使腳本更難以追蹤。您的情境可能會在您下載檔案時結束,因為您的主要控制流程並未等待此操作完成。
注意
如需上傳檔案,請參閱上傳檔案章節。