python-3.x - 下载带有请求的 zip 文件时,文件最终被损坏
问题描述
为什么使用请求下载的 zip 文件最终会损坏?试图制作一个在指定时间开始下载的程序。
import requests
import time
import datetime
tim = datetime.datetime.now()
print("########So Far Only Works With mp4, png, jpg, pkg and exe files########")
time.sleep(1)
DLTime = input("Time\nHH:MM\n")
url = input("URL:\n")
Location = ("/Users/'user'/Downloads/" + input("File Name\n"))
print("Waiting...")
while(True):
tim = datetime.datetime.now()
if tim.strftime("%H:%M") == DLTime:
print("Download Started")
myfile = requests.get(url)
open(Location, 'wb').write(myfile.content)
print("\nDownload Finished")
input("Press Enter To Finish")
exit()
time.sleep(1)
注意:由于与代码的其他部分的干扰,不得不使用 tim 而不是 time。
注意:用户替换为“用户”。
解决方案
欢迎来到 StackOverflow!我不确定你的具体问题是什么,但是我看到你的代码有很多其他问题,所以我重写了它:
import datetime
import time
import requests
time_begginning = datetime.datetime.now()
print("########So Far Only Works With mp4, png, jpg, pkg and exe files########")
time_provided_raw = input('Enter the time you want to download the file (format HH:MM): ')
time_provided = datetime.datetime.strptime(time_provided_raw, "%H:%M")
url_to_retreive = input('Enter the url from where to download the file: ')
file_name_to_save = input('Enter the file name you want to save this file: ')
destination = f"/Users/'user'/Downloads/{file_name_to_save}"
scheduled_time = time_begginning.replace(hour=time_provided.hour,
minute=time_provided.minute,
second=0, microsecond=0)
if scheduled_time < time_begginning:
scheduled_time += datetime.timedelta(days=1)
timestamp_now = datetime.datetime.now().timestamp()
timestamp_schedule = scheduled_time.timestamp()
delay_to_wait = timestamp_schedule - timestamp_now
print('Waiting…')
time.sleep(delay_to_wait)
print("Download Started")
file_retreived = requests.get(url_to_retreive)
print("Download finished")
with open(destination, 'wb') as destination_file:
print(f'Saving to {destination}')
destination_file.write(file_retreived.content)
我没有通过循环检查每秒是否是正确的时间会让你的 CPU 忙碌,我:
- 收集所有需要的信息
- 计算下载前我们需要等待多长时间
- 如果输入的时间是过去的,我想这意味着我们必须等到明天
- 在那段时间里睡一次(而不是每秒醒来一次)
- 下载文件
- 使用提供的名称保存该文件
我已经在网上尝试了几个不同的 zip 文件,它似乎可以工作。
推荐阅读
- python - Python - 显示路径,简单的套接字问题
- tortoisegit - 将 AD 与 tortoiseGit 一起使用
- java - 在有向无环图中检测循环引用
- ios - 安全更新 NSManagedObjects 的键值
- sql-server - 基于集合的堆叠更新查询
- google-cloud-platform - 如何使用 terraform 创建 gcr 存储库?
- python - 自动无法单击 Webdriver 中的元素(python)
- floating-point - 浮点数的金属 SIMD 最小值和最大值操作失败
- php - PHP - Zend3、Jquery、Ajax(帖子)
- google-chrome - 用于跟踪搜索字符串的浏览器插件/扩展