Wait for Download to finish in selenium webdriver JAVA

后端 未结 13 1605
醉话见心
醉话见心 2020-12-01 14:38

Once clicking a download button, files will be downloaded. Before executing next code, it needs to wait until the download completes.

My code looks like this:

<
相关标签:
13条回答
  • 2020-12-01 15:15

    If you are using chrome for the download, the you can use the below method to make sure the script will wait until the download is completed.

    Python Implementation:

    def waitUntilDownloadCompleted(maxTime=600):
        driver.execute_script("window.open()")
        # switch to new tab
        driver.switch_to.window(driver.window_handles[-1])
        # navigate to chrome downloads
        driver.get('chrome://downloads')
        # define the endTime
        endTime = time.time() + maxTime
        while True:
            try:
                # get the download percentage
                downloadPercentage = driver.execute_script(
                    "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")
                # check if downloadPercentage is 100 (otherwise the script will keep waiting)
                if downloadPercentage == 100:
                    # exit the method once it's completed
                    return downloadPercentage
            except:
                pass
            # wait for 1 second before checking the percentage next time
            time.sleep(1)
            # exit method if the download not completed with in MaxTime.
            if time.time() > endTime:
                break
    

    Just call the method when ever you click on download link/button.

    # click on download button
    driver.find_element_by_xpath("//*[@id='perform']").click()
    #wait until the download completed
    waitUntilDownloadCompleted(120) #2 minutes
    
    0 讨论(0)
提交回复
热议问题