Selenium not waiting for file to download and continues ignoring while loop

Viewed 100

I'm writing a script to download some youtube videos into mp3 and want the code to start a single download and after that continue with the other and the other and so on. The thing is, after the first download finishes, something brokes and starts to skipping download and not waiting for the download to finish to continue. Here's what I wrote, hope you can help me:

    for names in items:
    stringName = "".join(names)
    driver.get("https://www.youtube.com/results?search_query=" + stringName)
    time.sleep(6)
    driver.find_element_by_xpath("//a[@id='video-title']").click()
    songLink = driver.current_url
    driver.get("https://ytbmp3.club/")
    driver.find_element_by_id("dlURL").send_keys(songLink, Keys.RETURN)


    driver.find_element_by_xpath("//iframe[@class='embed-responsive-item']").click()
    time.sleep(10)
    wait = True
    while (wait == True):
        for fname in os.listdir('C:\\Users\\sdf\\Desktop\\pruebatelgspo'):
            if ('.crdownload') in fname:
                print('downloading files ...')
                time.sleep(10)
            else:
                wait = False
    print('finished downloading all files ...')
1 Answers
while (wait == True):
    for fname in os.listdir('C:\\Users\\sdf\\Desktop\\pruebatelgspo'):
        if ('.crdownload') in fname:
            print('downloading files ...')
            time.sleep(10)
        else:
            wait = False

This is the troublemaker section:

You first set wait = True and initiate the while loop to continue if wait == True. Now you go through all the filenames in your given directory and check one by one if .crdownloadis in the name. Now occurs the problem: The first time your script runs through the else-section wait is set to False, which will result in the while-statement not being fulfilled and hence cancelling.

Therefore, the while-loop will be left even if there are still files with .crdownload in the directory, just because you ran "through" the else-block.


A suggestion to fix this issue:

while wait == True:
    if any('.crdownload' in n for n in os.listdir('C:\\Users\\sdf\\Desktop\\pruebatelgspo'):
    continue
else:
    break

You could also replace break with wait = False, depending on which syntax better suit your future needs in the software you're writing.

Related