michaeluskov
michaeluskov

Reputation: 1828

Urllib2 downloads broken binary data

Here is sample code of downloading images using urllib2:

for photo in getListOfPhotos('Anouk'):
    with open(photo[0]+'.jpg','w+') as f:
        response = urllib2.urlopen(photo[1])
        answer = response.read()
        while answer:
            f.write(answer)
            f.flush()
            answer = response.read() 

(assuming that photo is list where first item is file name and second item is link)

But I get broken pictures (with green lines, red squaers etc). What's wrong?

Upvotes: 0

Views: 265

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can use urllib.urlretrieve to download an image, you pass the image url and the directory/name_to_save_as as the second parameter.

import urllib

urllib.urlretrieve(image_url,"locataion_to_save")

Upvotes: 1

Related Questions