-2
在這裏,我試圖從網址列表(largest_images)下載圖像。我只想下載一張圖片。當圖像下載成功時,我希望for循環立即停止。我很難弄清楚在哪裏把break語句放在下面的代碼中。當文件下載完成時打破for循環
for image_url in largest_images:
# SOME VARIABLES
timeout = 20
response = None
file_name = md5(image_url)
file_path = os.path.join(dst_dir, file_name)
try_times = 0
while True:
try:
try_times += 1
response = requests.get(image_url, headers=headers, timeout=timeout)
if response.status_code == 200:
print "Downloading: %s" % image_url
with open(file_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
response.close()
file_type = imghdr.what(file_path)
# if file_type is not None:
if file_type in ["jpg", "jpeg", "png", "bmp"]:
new_file_name = "{}.{}".format(file_name,file_type)
new_file_path = os.path.join(dst_dir, new_file_name)
shutil.move(file_path, new_file_path)
print ("## OK: {} {}".format(new_file_name, image_url))
break (I have added a break statement here, but its not working)
else:
os.remove(file_path)
print ("## Err: {}".format(image_url))
break
except Exception as e:
if try_times < 3:
continue
if response:
response.close()
print ("## Fail: {} {}".format(image_url, e.args))
break
只要取出除了一個,並保持在嘗試中的一個 –