Tuesday, April 8, 2025

How to Download Files with Playwright

In Playwright, you can download files by listening for the download event and saving the file once it is triggered. The download event is fired whenever a download is initiated, allowing you to interact with the file and specify where to save it.

How to Download Files with Playwright



Here's how you can handle file downloads in Playwright:

Steps to Download a File in Playwright:
  1. Intercept the download event: Listen for the download event that is triggered when a download starts.
  2. Save the file: You can specify the path where you want to save the downloaded file.

Syntax :
 // Start waiting for download before clicking. Note no await.
  const downloadPromise = page.waitForEvent('download'); 
  await page.locator('//span[contains(text(),"WinRAR 7.11 English 64 bit")]').click();
  const download = await downloadPromise;

  // Wait for the download process to complete and save the downloaded file somewhere.
  await download.saveAs('download/' + download.suggestedFilename());

Example :
// @ts-check
import { test, expect } from '@playwright/test';
import fs from 'fs';


test('download file from webpage', async ({page}) => {

  await page.goto('https://www.win-rar.com/download.html?&L=0');
  
  // Start waiting for download before clicking. Note no await.
  const downloadPromise = page.waitForEvent('download'); 
  await page.locator('//span[contains(text(),"WinRAR 7.11 English 64 bit")]').click();
  const download = await downloadPromise;

  // Wait for the download process to complete and save the downloaded file somewhere.
  await download.saveAs('download/' + download.suggestedFilename());
  
  // Assert filename.
  expect(download.suggestedFilename()).toBe("winrar-x64-711.exe");

  // Get size of downloaded file.
  expect((await fs.promises.stat(await download.path())).size).toBeGreaterThan(200);

});  

Once you have executed the above playwright script, it will download file in 'download' folder

How to Download Files with Playwright






No comments:

Post a Comment