1

I have a program that downloads a file using selenium and then gets the file name with os.listdir.

My problem right now is that the download takes too long, and my code has moved on with the process. How can I pause the code until the file is downloaded?

Is there a selenium wait until download complete, or a way for selenium to pass the downloaded files name into a variable that i can plug into the answer from here

driver.find_element(By.XPATH, '//button[text()="Export to CSV"]').click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Download"]')))
driver.find_element(By.XPATH, '//button[text()="Download"]').click()
files=os.listdir(folderPath)#finds all files in folder
print(files)
NarendraR
  • 7,577
  • 10
  • 44
  • 82
Calvin Hobbes
  • 77
  • 1
  • 7

3 Answers3

4

The clear answer of you question is No. Selenium don't have such method to wait until download get completed.

You can write your own custom method which check downloaded file name in download directory continuously in some time interval.

def is_file_downloaded(filename, timeout=60):
    end_time = time.time() + timeout
    while not os.path.exists(filename):
        time.sleep(1)
        if time.time() > end_time:
            print("File not found within time")
            return False

    if os.path.exists(filename):
        print("File found")
        return True

Call that method just after code line which hits download.

driver.find_element(By.XPATH, '//button[text()="Download"]').click()
file_path = '/Users/narendra.rajput/Documents/30.docx'
if is_file_downloaded(file_path, 30):
    print("yes")
else:
    print("No")
NarendraR
  • 7,577
  • 10
  • 44
  • 82
0

If there is a DOM change event happening after the download is complete then you can wait for that event using selenium predefined waits, else the only option is to wait until the file exists in the location as mentioned in the link in your question.

Kumar Rishabh
  • 292
  • 1
  • 9
0

There may be no Selenium wait method so to wait until the file download get completed. A custom function may be written for this to check file download. If an exact file name is not known but file name start with some fixed name and followed by timestamp or some marker etc. suppose 'abcd123.csv', 'abcd456.csv' or 'abcd789ty.csv', one can use While True loop to check for the file download.

import os, glob

path = 'C:/Users/'+os.getlogin()+'/Downloads/'

driver.get('https://abcd.com/sr/abc.views:request-csv-/12345/SearchRequest-27801.csv')

while True:
    file = glob.glob(path+'abcd'+'*'+'.csv')
    old_file = ' '.join([str(f) for f in file])
    if os.path.exists(old_file):
        break

driver.quit()


new_file = path+'abcd.csv'
if os.path.exists(old_file):
    os.rename(old_file,new_file)
Souvik Daw
  • 129
  • 7