Search code examples
pythonurllib2

Using urllib.request to write an image


I am trying to use this code to download an image from the given URL

import urllib.request

resource = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
output = open("file01.jpg","wb")
output.write(resource)
output.close()

However, I get the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-39-43fe4522fb3b> in <module>()
     41 resource = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
     42 output = open("file01.jpg","wb")
---> 43 output.write(resource)
     44 output.close()

TypeError: a bytes-like object is required, not 'tuple'

I get that its the wrong data type for the .write() object but I don't know how to feed resource into output


Solution

  • Right, Using urllib.request.urlretrieve like this way:

    import urllib.request
    
    resource, headers = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
    image_data = open(resource, "rb").read()
    with open("file01.jpg", "wb") as f:
        f.write(image_data)
    

    PS: urllib.request.urlretrieve return a tuple, the first element is the location of temp file, you could try to get the bytes of temp file, and save it to a new file.

    In Official document:

    The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.


    So I would recommend you to use urllib.request.urlopen,try code below:

    import urllib.request
    
    resource = urllib.request.urlopen("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
    output = open("file01.jpg", "wb")
    output.write(resource.read())
    output.close()