Download a File using Playwright

Tutorial 17​​ ​​ Download a File using​​ Playwright​​ 

What you will Learn​​ in this​​ blog:

  • Download a file using PW

  • Code snippets

Download a file using PW

Let us​​ now see how to​​ download a file using PW.

We will download a file from​​ the​​ test website page

https://the-internet.herokuapp.com/download​​ 

Create a new test file

Go to the official documentation page to download a file using Playwright

https://playwright.dev/docs/api/class-download​​ 

Copy the above code snippet​​ and paste it inside the test block

Right click and ‘Format Document’

The code gets formatted​​ 

Let us now add a line to launch the webpage

Inspect any file​​ 

Copy the highlighted text and paste it as shown below

Next, let us log the path​​ where the file gets downloaded temporarily during runtime

Save and execute the command in ‘debug’ mode. This mode opens the playwright inspector​​ 

Notice that the blank chromium browser gets launched alongwith the playwright inspector having ‘Step over’ button

Click ‘Step over’.​​ 

Notice that the webpage is loaded and we are right now on line#11 (see inspector)

Click ‘Step over’.

Notice that the file gets downloaded

 

Click ‘Step over’.

The script gest over and the console log shows the temp path. The test passes

Let us now log the path​​ of file url

Saver and execute.

Notice that the file url (alongwith the filename) too can be seen in the console

So this is how we can download a file using PW.

Code snippet

import​​ {​​ test,​​ expect​​ }​​ from​​ '@playwright/test'

 

test("file download operation",​​ async​​ ({​​ page​​ })​​ =>​​ {

   await​​ page.goto('https://the-internet.herokuapp.com/download')

   // Note that Promise.all prevents a race condition

   // between clicking and waiting for the download.

   const​​ [download] =​​ await​​ Promise.all([

     ​​ // It is important to call waitForEvent before click to set up waiting.

     ​​ page.waitForEvent('download'),

     ​​ // Triggers the download.

     ​​ page.locator('text=LambdaTest.txt').click(),

   ]);

   // wait for download to complete

   const​​ path​​ =​​ await​​ download.path();

   console.log(path)

 

   const​​ url​​ =​​ await​​ download.url();

   console.log(url)

})

 

 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 1st Nov 2024