Playwright Download File

Playwright Download File

The playwright can also download a file and save it to a default path. Download objects are dispatched via page.on('download') event.

The download files that belong to the browser context are deleted when the context is closed. We can see that the download event is set on course once it starts, and the path is available when it gets completed.

Here is the syntax:

const [ download ] = await Promise.all([
  page.waitForEvent('download'),
  page.locator('text=Download file').click(),
]);
const path = await download.path();
  • The download is wrapped inside the promise.all to prevent race conditions between clicking and waiting for the download.
  • The locator inside the promise clicks on the download button, which triggers the download.
  • Before that playwright is said to wait for the event till the download happens.
  • After it has been done path can be seen in the output.

Example:

Let us see it in real-time.

const {test, expect} = require('@playwright/test');
const pageWithFiles = "http://demo.automationtesting.in/FileDownload.html";

test('ElementHandle', async ({page})=> 
{

    
    await page.goto(pageWithFiles);
   
    const [ download ] = await Promise.all([
        page.waitForEvent('download'), 
        page.click("a[type='button']"),
        
    ]);
    const path = await download.path();
    console.log(path);

});
  • Here is the same syntax with a real-time working download example.
  • So here it is wrapped inside the promise to avoid a race condition between the wait and click.
  • Once that is done, the file will be downloaded successfully.

In windows, the path to the download file looks something like this.

C:\Users\arili\AppData\Local\Temp\playwright-artifacts-TXNHDw\3e95cb75-6df1-4a8f-8e2e-edadf50d4979

  • We can also save the file into the desired path using,
await download.saveAs(desiredPath);

Conclusion:

Downloading a file in playwright is very simple and downright smooth with a straightforward and reliable API.

Tags
Standard (Image)