Jump to content

Wikipedia:Scripts/ImageFileMigrator/ImageDownloader.py

From Wikipedia, the free encyclopedia
#!/usr/bin/env python
import urllib
import os
class ImageDownloader:
    def __init__(self, urlBase, savePath):
        self.urlBase = urlBase
        self.path = savePath
        if not os.path.exists(savePath):
            os.mkdir(savePath)
        self.images = {}    
    def _saveImage(self, url):
        location = url.split('/')[-1]
        self.images[url] = False
        ImageDownload(location, self.urlBase + url, self.path + location)
        #Use the following variation if wiki is not installed at root of domain
        #ImageDownload(location, self.urlBase + '/images/' + url.split('/images/')[1], self.path + location)
    def saveImages(self, urls):
        for url in urls:
            self._saveImage(url)
        

class ImageDownload:
    def __init__(self,name, url, savePath):
        self.url = url
        self.name = name
        self.percent = 0
        urllib.urlretrieve(url, savePath, lambda x, y,z: (self.downloadUpdate(x,y,z)))
    def downloadUpdate(self, x,y,z):
        percent = int(x*y/float(z)*100)
        percent = min(100, percent)
        if percent > self.percent:
            self.percent = percent
            print str(percent) + "% " + self.name