我想在网站上下载每 15 秒刷新一次的 JPG 图像,以获得一组文件,这些文件可以稍后由视频延时程序组装。我正在使用 Python ver.3,但我对提供的大量建议、文件的打开和关闭感到不知所措。没有一个简单的命令可以在不打开文件的情况下获取文件,并将其存储在其名称中的索引中吗?
问问题
387 次
1 回答
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)
于 2013-08-13T01:48:06.567 回答