如何使用 urllib 2 在 django-python 2.7 中使用 url 下载和上传图像
How can I download and upload an image using a url in django-python 2.7 using urllib 2
我正在使用 beautiful soup 从 Foodily-food website 抓取数据。我是 python 的新手,所以我对 python 中的文件处理知之甚少,我的要求是从 url 上方抓取数据,然后下载图像并将其上传到我的项目中。
我使用以下方法获得了图像的 src:
image = soup.find("img",{"itemprop":"image"})['src']
现在我需要下载这张图片然后上传。
我使用下面的代码来检索图像并阅读它:
img = urllib2.urlopen(image)
html = img.read()
return HttpResponse(html)
我得到了某种编码形式的输出,不知道如何进一步处理它。
如有任何指导,我们将不胜感激。
我使用请求和 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
使用 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)
请注意 python2 and python3 中的 urllib2 不同。
关于django,请看一下https://github.com/divio/django-filer and/or https://github.com/SmileyChris/easy-thumbnails正确保存图片
此外,要下载图像,请按照 jinkspadlock 的建议查看 http://docs.python-requests.org/en/master/。
我正在使用 beautiful soup 从 Foodily-food website 抓取数据。我是 python 的新手,所以我对 python 中的文件处理知之甚少,我的要求是从 url 上方抓取数据,然后下载图像并将其上传到我的项目中。
我使用以下方法获得了图像的 src:
image = soup.find("img",{"itemprop":"image"})['src']
现在我需要下载这张图片然后上传。 我使用下面的代码来检索图像并阅读它:
img = urllib2.urlopen(image)
html = img.read()
return HttpResponse(html)
我得到了某种编码形式的输出,不知道如何进一步处理它。
如有任何指导,我们将不胜感激。
我使用请求和 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
使用 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)
请注意 python2 and python3 中的 urllib2 不同。 关于django,请看一下https://github.com/divio/django-filer and/or https://github.com/SmileyChris/easy-thumbnails正确保存图片
此外,要下载图像,请按照 jinkspadlock 的建议查看 http://docs.python-requests.org/en/master/。