Skip to content

Instantly share code, notes, and snippets.

@013
Created November 25, 2012 19:14
Show Gist options
  • Save 013/4144841 to your computer and use it in GitHub Desktop.
Save 013/4144841 to your computer and use it in GitHub Desktop.
Random imgur downloader
#!/usr/bin/python
import sys, urllib, urllib2, random, string
def random_image():
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
rand_img = ''.join(random.choice(chars) for x in range(5))
base = 'http://i.imgur.com/%s.png' % rand_img
return base
def content_headers(url):
res = urllib2.urlopen(url)
meta = res.info()
c_length = int(meta.getheaders("Content-Length")[0])
c_type = meta.getheaders("Content-Type")[0]
return c_length, c_type
def gen_list(size):
images = []
while len(images) != size:
url = random_image()
length, imgtype = content_headers(url)
if imgtype == 'image/jpeg':
url = url.replace('png', 'jpg')
elif imgtype == 'image/gif':
url = url.replace('png', 'gif')
if length != 503:
print "%d/%d image(s) found.." % (len(images)+1, size)
images.append(url)
return images
if __name__ == "__main__":
total_images = int(sys.argv[1])
print "\nGenerating a list with %d link(s)..." % total_images
images = gen_list(total_images)
for link in images:
print link
urllib.urlretrieve(link, './image/%s' % link.split('/')[-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment