之前爬取的数据,是直接把图片url放在Excel中的,或者直接下载到一个目录中,或者转存到自家服务器上,拿到新的链接。
这边收到需求要求把图片缩小到140*140直接放到Excel单元格中,操作如下。
使用Requests下载图片
使用Requests下载单张图片,只要将相应对象的二进制内容,二进制格式保存即可,示例如下:
import requests
url = 'https://www.bulgari.cn/media/catalog/product/cache/17a97ae74dcd05e3600304dfd5afbc49/3/5/356325_001.png'
res = requests.get(url)
file_name = url.split('/')[-1]
with open(file_name, 'wb') as f:
f.write(res.content)
如果图片较大,为了优化性能,可以分块写入:
...
with open(file_name, 'wb') as f:
for data in res.iter_content(128):
f.write(data)
使用openpyxl,在Excel中插入图片
使用openpyxl,可以使用sheet对象的add_image('图片文件路径或Image对象', '锚点')来在一个单元格中插入对象,使用openpyxl中的Image对象还可以设置图片尺寸。示例如下。
from openpyxl