Skip to content

Instantly share code, notes, and snippets.

@cuadue
Created July 12, 2012 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuadue/3099475 to your computer and use it in GitHub Desktop.
Save cuadue/3099475 to your computer and use it in GitHub Desktop.
random imgur downloader
#!/usr/bin/env python
import os
import sys
import random
import time
from urllib2 import Request, urlopen, URLError, HTTPError
CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz"
# functions
def rand_string(string_length):
return ''.join(random.choice(CHARS) for _ in xrange(string_length))
def get_images(num_pics):
path = os.path.join(os.getcwd(), '/output')
if not os.path.exists(path):
os.makedirs(path)
print 'saving to: ' + path
for k in xrange(num_pics):
good = False
while not good:
img_name = rand_string(5)
url = "http://i.imgur.com/" + img_name + ".jpg"
req = Request(url)
try:
f = urlopen(req)
print "downloading " + url
with open(os.path.join(path, img_name, '.jpg'), "wb") as local_file):
local_file.write(f.read())
except HTTPError, e:
print "HTTP Error:",e.code , url
print 'trying again...'
except URLError, e:
print "URL Error:",e.reason , url
print 'trying again...'
else:
good = True
if __name__ == '__main__':
start_time = time.time()
# syntax: random_imgur.py <how_many>; defaults to 5 if no input
HOW_MANY = int(sys.argv[1]) if len(sys.argv) > 1 else 5
print 'getting ' + str(HOW_MANY) + ' random pics'
get_images(HOW_MANY)
print 'done!'
end_time = time.time()
print 'completed in: ' + str(round(end_time - start_time, 2)) + ' seconds'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment