Ronald Saunfe
Ronald Saunfe

Reputation: 651

Download file using python without knowing its extension. - content-type - stream

Hey i just did some research and found that i could download images from urls which end with filename.extension like 000000.jpeg. i wonder now how i could downoad a picture which doesnt have any extension. Here is my url which i want to download the image http://books.google.com/books/content?id=i2xKGwAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api when i put the url directly to the browser it displays an image

furthermore here is what i tried:

from six.moves import urllib

thumbnail='http://books.google.com/books/content?id=i2xKGwAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api'

img=urllib.request.Request(thumbnail)
pic=urllib.request.urlopen(img)
pic=urllib.request.urlopen(img).read()

Anyhelp will be appreciated so much

Upvotes: 0

Views: 3483

Answers (1)

Loïc
Loïc

Reputation: 11943

This is a way to do it using HTTP response headers :

import requests
import time

r = requests.get("http://books.google.com/books/content?id=i2xKGwAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api", stream=True)
ext = r.headers['content-type'].split('/')[-1] # converts response headers mime type to an extension (may not work with everything)
with open("%s.%s" % (time.time(), ext), 'wb') as f: # open the file to write as binary - replace 'wb' with 'w' for text files
    for chunk in r.iter_content(1024): # iterate on stream using 1KB packets
        f.write(chunk) # write the file

Upvotes: 6

Related Questions