Search code examples
djangopython-2.7beautifulsoupurllib2

How can I download and upload an image using a url in django-python 2.7 using urllib 2


I am using beautiful soup to scrap data from Foodily-food website. I am new to python so I have litle knowledge of file handling in python, my requirement is to scrap data from above above url and then download an image and uploading that to my project.

I have got src of image using:

image = soup.find("img",{"itemprop":"image"})['src']

Now I need to download this image and then upload it. I have used below code to retrieve image and read it:

 img = urllib2.urlopen(image)
    html = img.read()
    return HttpResponse(html)

I have got output in some encoded form and don't what to do further with it.

Any guidance would be appreciated.


Solution

  • Save an image with urllib2

    import urllib2
    img_src = 'https://unsplash.it/500/300'
    
    response = urllib2.urlopen(img_src)
    image = response.read()
    
    with open('your_image_name.jpg', 'wb') as out:
        out.write(image)
    

    Please note that urllib2 is different in python2 and python3. Regarding django, please take a look at https://github.com/divio/django-filer and/or https://github.com/SmileyChris/easy-thumbnails to save images properly.

    Further, to download the images, take a look at http://docs.python-requests.org/en/master/ as jinkspadlock suggested.