Selenium (Python) - waiting for a download process to complete using Chrome web driver

后端 未结 9 1170

I\'m using selenium and python via chromewebdriver (windows) in order to automate a task of downloading large amount of files from different pages. My code works, but the so

9条回答
  •  春和景丽
    2020-12-04 18:53

    import os
    from selenium import webdriver
    from selenium.webdriver.support.wait import WebDriverWait
    
    class MySeleniumTests(unittest.TestCase):
    
        selenium = None
    
        @classmethod
        def setUpClass(cls):
            cls.selenium = webdriver.Firefox(...)
    
        ...
    
        def test_download(self):
            os.chdir(self.download_path) # default download directory
    
            # click the button
            self.selenium.get(...)
            self.selenium.find_element_by_xpath(...).click()
    
            # waiting server for finishing inner task
            def download_begin(driver):
                if len(os.listdir()) == 0:
                    time.sleep(0.5)
                    return False
                else:
                    return True
            WebDriverWait(self.selenium, 120).until(download_begin) # the max wating time is 120s
    
            # waiting server for finishing sending.
            # if size of directory is changing,wait
            def download_complete(driver):
                sum_before=-1
                sum_after=sum([os.stat(file).st_size for file in os.listdir()])
                while sum_before != sum_after:
                    time.sleep(0.2)
                    sum_before = sum_after
                    sum_after = sum([os.stat(file).st_size for file in os.listdir()])
                return True
            WebDriverWait(self.selenium, 120).until(download_complete)  # the max wating time is 120s
    

    You must do these thing

    1. Wait for server to finish inner business( for example, query from database).
    2. Wait for server to finish sending the files.

    (my English is not very well)

提交回复
热议问题