Location>code7788 >text

A First Look at the "New Out of the Box" Series - Python+Playwright Automation Test-58 - File Download

Popularity:774 ℃/2024-07-30 11:22:54

1. Introduction

After the previous articles explain how to upload files, since there is uploading, then there may be downloading files. Therefore, Hong will continue to explain and share: automated testing download files. There may be small partners or children's shoes will feel that this is not very simple, but also with your introduction and explanation ah, not to say that is to visit the download page, and then locate the file to be downloaded after the download button, click the button on it. In fact, this is not the case, and listen to the macro brother Xu Dao: macro brother here to download is to remove the download pop-up box download. We can see in the download file will pop up a Windows dialog box, we know, selenium can only operate the web page, can not operate the Windows dialog box, in the Selenium tutorials, about this part of the explanation is the use of browser parameters to prohibit the download of pop-up windows or the use of tools autoIT or keyboard simulation. The tutorial on Selenium explains how to disable download popups using browser parameters or using autoIT or keyboard simulation. So how does Playwright realize the file download?

2. Download file API

Playwright is a modern automated testing tool that supports a wide range of browsers and operating systems, helping developers and testers easily build and run reliable end-to-end tests. In addition to its testing features, Playwright offers several utilities and APIs, including file upload and download features. These features help users simulate scenarios where a user uploads or downloads a file and verify that these operations are performed as expected. In this article, we will explore how to implement file uploads in Playwright and provide some sample code and best practices.
For example: the platform above the upload function, will provide a template (such as excel, csv), at this time, we need to download the template, modify the completed, and then uploaded, as a tester, we need to verify that it has been downloaded to the local. playwright can be achieved without the use of other tools to download the file.

The download file introduces the documentation address of the official API:Downloads | Playwright Python

2.1 Download file syntax

# Start waiting for the download
with page.expect_download() as download_info:
    # Perform the action that initiates download
    page.get_by_text("Download file").click()
download = download_info.value

# Wait for the download process to complete and save the downloaded file somewhere
download.save_as("/path/to/save/at/" + download.suggested_filename)

From the above syntax we know that playwright provides the expect_download() operation for file download operations, but pay special attention to the fact that all downloaded files belonging to the browser context are deleted when the browser context is closed. The download event is emitted when the download starts. When the download is complete, the download path is available.

Related operations

3.1 Canceling downloads

Cancel the download. If the download has been completed or canceled, it will not fail. Upon successful cancellation, () will resolve to 'canceled'.

()

3.2 Deleting downloads

Delete the downloaded file. If necessary, will wait for the download to complete.

()

3.3 Return download errors (if any)

Returns the download error (if any). Will wait for the download to complete, if necessary.

()

3.4 Get the page to which the download belongs

Get the page to which the download belongs.


3.5 Download Path

If the download is successful, the path to the downloaded file is returned. If necessary, the method will wait for the download to complete. This method is thrown on remote connection.
Note that the downloaded filename is a random GUID, use download.suggested_filename to get the suggested filename.

() #come (or go) backNoneType| typology

3.6 Copying downloads to a user-specified path

Copies the download to a user-specified path. It is safe to call this method while the download is still in progress. If necessary, it will wait for the download to complete.

download.save_as(path)

3.7 Return the suggested filename for this download

Returns the suggested filename for this download.
It is typically used by the browser to create a customized image based on theContent-DispositionRespond to the header ordownloadattribute is calculated. See the specification on whatwg. Different browsers can use different logic to calculate it.

download.suggested_filename

3.8 Returning the downloaded URL

Returns the url of the download.


4.Project practice

Hiro is on this site:/demo/ I found an example of an online now file, and I'm here to show it to my buddies or kids.

4.1 Code design

4.2 Reference code

# coding=utf-8🔥

# 1. First set the encoding, utf-8 can support Chinese and English, such as the above, generally placed in the first line

# 2. Notes: including record creation time, creator, project name.
'''
Created on 2024-05-07
@author: Beijing, capital of People's *-* businessman
Public No.: Beijing Hongge (WeChat search: Beijing Hongge, follow Hongge, unlock more testing dry goods in advance!)
Project: "The latest out of the box" series of first peek - Python + Playwright automation testing - 58 - File Download
'''

# 3. Import module

from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
    browser = (headless=False)
    context = browser.new_context()
    page = context.new_page()
    ("/demo/")
    page.wait_for_timeout(1000)
    with page.expect_download() as download_info:
        page.get_by_text("").click()
    download = download_info.value
    # wait for download to complete
    print()  # Get the url of the download
    # This step just downloads it and generates a random uuid value to save, which is automatically cleared after the code is executed
    print(())
    name = download.suggested_filename # get suggested name
    file = f"download/{name}" # file path    download = download_info.value
    # Eventually you can save it locally with save_as
    download.save_as(file) # download file
    page.wait_for_timeout(1000)
    print("browser will be close")
    # ()
    # ()
    # ()
    ()
with sync_playwright() as playwright:
    run(playwright)

4.3 Running the code

1. Run the code, right click Run 'Test', you can see the console output, as shown below:

2. Run the code after the computer side of the browser's actions (the bottom left corner of the browser to download the file). As shown in the figure below:

3. You can see that the file has been successfully downloaded to Hong's local computer default download path, as shown below:

5. Summary

This article mainly introduces the use of playwright to achieve automated file downloads, compared to selenium, playwright file downloads are more powerful, do not need to use other tools to be able to realize. Macro here to explain and share the Chrome browser to download files, other browsers are similar, interested partners or children can try it themselves. Well, time is running out, about playwright download file first introduced to explain here, thank you for your patience to read!