• How to download a file
  • How to save the downloaded file
  • Conclusion
None

Download a file

We will use the demo page for downloading a file of demoqa.com to test our code. https://demoqa.com/upload-download

On the page, there is a button named Download.

None

Firstly, we should open the web page.

page.goto("https://demoqa.com/upload-download")

We should wait for the download result because it will take some time for downloading a file after clicking the download button. We can use the expect_download() method of the page object to wait for the download finished. When the download is finished, the information of the download will be returned. You can download a file using Playwright as below.

with page.expect_download() as download_info:     
    page.locator("a:has-text(\"Download\")").click()

The download_info will accept the download result.

Save the downloaded file

We can get the download result from the value property of download_info.

download = download_info.value

And we can get the original file name using the suggested_filename property of download. It is typically computed by the browser from the Content-Disposition response header or the download attribute.

file_name = download.suggested_filename

Next, let's decide where to save this file. Here we will save the file to the data folder and use a relative path.

destination_folder_path = "./data/"

Finally, let's save the download result to the specified destination path. Here we use the original file name, of course, you can specify your own file name.

download.save_as(os.path.join(destination_folder_path, file_name))

Below is the complete code.

When execution is finished, you should see the downloaded image file in your data folder.

None

Conclusion

We can wait for the download result to return by using the expect_download() method after clicking the download button. And use download info to get the original file name and use save_as() method to save the downloaded file to the specified path as the specified file name.

If you want to learn the basic usage of Playwright, you can read the article below.

Playwright " Basic Usage https://thats-it-code.com/playwright/playwright__basic-usage/

Originally published at https://thats-it-code.com on March 25, 2022.