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.

Community
  • 1
  • 1
Always_a_learner
  • 4,585
  • 13
  • 63
  • 112

2 Answers2

3

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.

Community
  • 1
  • 1
wiesson
  • 6,544
  • 5
  • 40
  • 68
0

I use requests and shutil:

import requests
import shutil

response = requests.get(iconurl, stream=True)
with open(iconfilepath, 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response