Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Feb 5th, 2013  |  syntax: Python  |  size: 0.68 KB  |  views: 31  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import requests  # because using urllib2 is like pulling teeth
  2. import mimetypes # so we can get the file extension correct
  3.  
  4. # request a random image (will result in a 302 redirect)
  5. random_response = requests.head("http://imgur.com/random")
  6.  
  7. # parse the filename out of the location header
  8. filename = random_response.headers["location"].split("/")[-1]
  9.  
  10. # request the actual image
  11. image = requests.get("http://i.imgur.com/{0}.png".format(filename))
  12.  
  13. # figure out what the file extension should be
  14. extension = mimetypes.guess_all_extensions(image.headers['content-type'])[-1]
  15.  
  16. # write file to disk
  17. with open("{0}{1}".format(filename, extension), "w") as f:
  18.     f.write(image.content)
clone this paste RAW Paste Data