python requests下載文件慢


使用python的三方庫 requests 在下載文件時,很慢。

源代碼:直接根據返回內容寫文件,文件並不是很大,但是寫起來很慢

     response = requests.post('https://xxxx', data=json.dumps(payload), headers=headers,
cookies=cookies, proxies=proxies)
     if response.content:
         with open(target_path, 'wb') as f:
              f.write(response.content)
         return response.text

 

調整后代碼:

 1 url="https://xx.gin.csv"
 2 response = requests.get(url, stream = True)
 3 
 4 text_file = open("data.txt","wb")
 5 for chunk in response.iter_content(chunk_size=1024):
 6     text_file.write(chunk)
 7 writing one chunk at a time to text file
 8 
 9 text_file.close()

 

 with requests.post('https://xx.com/download', data=json.dumps(payload), headers=headers,
                       cookies=cookies, proxies=proxies) as r:
        r.raise_for_status()
        with open(target_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=2048):
                # If you have chunk encoded response uncomment if
                # and set chunk_size parameter to None.
                # if chunk:
                f.write(chunk)
        delete_yhhd_file(cookies, file_code)  # 刪除文件請求

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM