Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests # because using urllib2 is like pulling teeth
- import mimetypes # so we can get the file extension correct
- # request a random image (will result in a 302 redirect)
- random_response = requests.head("http://imgur.com/random")
- # parse the filename out of the location header
- filename = random_response.headers["location"].split("/")[-1]
- # request the actual image
- image = requests.get("http://i.imgur.com/{0}.png".format(filename))
- # figure out what the file extension should be
- extension = mimetypes.guess_all_extensions(image.headers['content-type'])[-1]
- # write file to disk
- with open("{0}{1}".format(filename, extension), "w") as f:
- f.write(image.content)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement