Here's how you can handle file downloads in Playwright:
Steps to Download a File in Playwright:
- Intercept the download event: Listen for the download event that is triggered when a download starts.
- 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
No comments:
Post a Comment