gciriani
gciriani

Reputation: 679

Download Time Lapse Images in Python

I want to download a JPG image that is refreshed every 15 seconds in a web site to obtain a collection of files that can be later on assembled by a time lapse program for a video. I'm using Python ver.3 but I'm overwhelmed by the multitude of suggestions offered, opening and closing of files. Isn't there a simple command to fetch the file without opening it, and store it with an index in its name?

Upvotes: 0

Views: 483

Answers (1)

Brionius
Brionius

Reputation: 14118

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)

Upvotes: 1

Related Questions