Học Playwright tiếng Việt, Cộng đồng Playwright cho người Việt

Khóa học

[Vọc Playwright] Download

https://playwright.dev/docs/downloads

Giới thiệu

  • Mỗi khi có download file xảy ra, sự kiện page.on('download') sẽ được sinh ra.
  • Các file này sẽ được download ở trong một thư mục “tạm” của hệ thống.
  • Bạn có thể lấy ra download url, file name, payload stream từ Download object.
  • Bạn cũng có thể định nghĩa đường dẫn download mặc định bằng cách dùng option downloadsPath trong browserType.launch()
  • Lưu ý: File download sẽ bị xóa đi khi browser context download file này bị đóng đi.
  • Một ví dụ đơn giản về việc handle download trong Playwright
// Start waiting for download before clicking. Note no await.
const downloadPromise = page.waitForEvent('download');
await page.getByText('Download file').click();
const download = await downloadPromise;

// Wait for the download process to complete and save the downloaded file somewhere.
await download.saveAs('/path/to/save/at/' + download.suggestedFilename());
  • Trong trường hợp bạn không biết khi nào sự kiện download xảy ra, có thể handle bằng cách dùng page.on:
page.on('download', download => download.path().then(console.log));
  • Lưu ý là khi bạn handle theo dạng page.on như này, cần phải chú ý về flow xử lý.
    • Có thể test của bạn sẽ end trong khi bạn vẫn đang download file.
    • Thường do bạn quên await, nên test không chờ bạn download.

Trả lời