【问题标题】:Selenium not waiting for file to download and continues ignoring while loopSelenium 不等待文件下载并继续忽略 while 循环
【发布时间】:2020-12-21 22:23:31
【问题描述】:

我正在编写一个脚本来将一些 youtube 视频下载到 mp3 中,并希望代码开始一次下载,然后继续另一个和另一个等等。问题是,在第一次下载完成后,有些东西坏了,开始跳过下载,而不是等待下载完成继续。这是我写的,希望你能帮助我:

    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 ...')

【问题讨论】:

    标签: python selenium file download


    【解决方案1】:
    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
    

    这是麻烦制造者部分:

    您首先设置wait = True 并启动while 循环以继续如果wait == True。现在您浏览给定目录中的所有文件名,并一一检查名称中是否有.crdownload。 现在出现了问题:您的脚本第一次运行 else-section wait 时被设置为 False,这将导致 while 语句没有被执行并因此被取消。

    因此,即使目录中还有带有.crdownload 的文件,也会留下while循环,因为你“通过”了else块。


    解决此问题的建议:

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

    您也可以将break 替换为wait = False,具体取决于您正在编写的软件中哪种语法更适合您未来的需求。

    【讨论】:

    • 我不知道是否应该修复其他问题,但我将 else 语句中的 False 更改为 True,现在它甚至不会等待第一次下载完成
    • @MiguelArrieche 我没说你应该把它改成True。我只是指出了导致错误的原因,现在您应该根据自己的意愿对其进行修改。无论如何,我编辑了我的回复并提出了一些建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多