我想下载一个在网站上每15秒刷新一次的JPG图像,以获取一组文件,这些文件稍后可以通过视频的延时程序进行组合。我正在使用Python ver.3,但我对提供的众多建议,文件的打开和关闭感到不知所措。是不是有一个简单的命令来获取文件而不打开它,并在其名称中存储索引?
答案 0 :(得分:1)
import urllib.error
import urllib.request
import time
imageURL = 'http://YOUR-WEB-SITE.com/imageName.jpg'
directoryForImages = '/where/you/want/to/store/image/'
imageBaseName = 'basename'
extension = '.jpg'
maxLoops = 100
for imageNumber in range(0, maxLoops):
try:
# Open a file object for the webpage where you will get the image
f = urllib.request.urlopen(imageURL)
# Open the local file where you will store the image
imageF = open('{0}{1}{2}{3}'.format(directoryForImages, imageBaseName, imageNumber, extension), 'wb')
# Write the image to the local file
imageF.write(f.read())
# Clean up
imageF.close()
f.close()
except urllib.error.HTTPError: # The 'except' block executes if an HTTPError is thrown by the try block, then the program continues as usual.
print "Image fetch failed. Waiting another 15 seconds..."
time.sleep(15)