将网页中的图片读出来,写入到OSS
总要说点儿什么
由于工作的原因经常要用到大量网路上的文件,尤其是图片,上传到自己的图床。由于大部分的博客网站都有防盗链,以及防转发功能。只有用到自己的图床才安心。
这里我以阿里云的OSS为例,将网络取到图片的URL,放到我自己的图床。这样无论是编辑时在markdown中使用,或是引入前端图库都很和谐。
话不多说,上代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/25 上午19:50
# @Author : Mars Zhang
# @File : imgtooss.py
# @Version : 1.0
# 说明: code后有'#'是测试时加的或者需要修改的code
# 用法:
# 参考文档 阿里云OSS文档 https://help.aliyun.com/document_detail/32026.html?spm=5176.87240.400427.48.hkgD7h
import oss2
import requests
import io
import os
endpoint = '<your endpoint for OSS>'
auth = oss2.Auth('<your Access Key>', '<Your Security Key>')
bucket = oss2.Bucket(auth, endpoint, '<Your bucket Name>')
# 打开本地的一个文件列表,这部分今后可以由爬虫提供
f = open('/Users/Desktop/html/imgurl.txt')
# 将文件行给到列表对象
url_img_list = list(f)
# 遍历列表上传到OSS,后续把COS和七牛试了,毕竟便宜。
for pl in url_img_list:
# 去掉文件末尾的换行符
img_url = str(pl).replace("\n", "")
# 得到URL后的文件名
imageName = os.path.basename(img_url)
# 得到想要的图片
img = io.BytesIO(requests.get(img_url, timeout=300).content)
# 放到OSS
bucket.put_object(imageName, img.getvalue())
f.close()