0、解决urllib.error.URLError: 报错
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
一、https资源下载到本地
from urllib.request import urlretrieve
import os
def download(url, savepath='./'):
"""
download file from internet
:param url: path to download from
:param savepath: path to save files
:return: None
"""
def reporthook(a, b, c):
"""
显示下载进度
:param a: 已经下载的数据块
:param b: 数据块的大小
:param c: 远程文件大小
:return: None
"""
print("\rdownloading: %5.1f%%" % (a * b * 100.0 / c), end="")
filename = os.path.basename(url)
if not os.path.isfile(os.path.join(savepath, filename)):
print('Downloading data from %s' % url)
urlretrieve(url, os.path.join(savepath, filename), reporthook=reporthook)
print('\nDownload finished!')
else:
print('File already exsits!')
filesize = os.path.getsize(os.path.join(savepath, filename))
print('File size = %.2f Mb' % (filesize/1024/1024))
if __name__ == '__main__':
url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
download(url, savepath='./')
二、钉钉上传资源
def ddupload(self, route):
url = f'{dd_domain}/media/upload?access_token={self.access_token}'
data = {
"type": 'image',
"media": str(route),
}
files = {
'media': open(route, 'rb')
}
res_json = requests.post(url=url, data=data, files=files).json()
return res_json
三、python url转二维码
pip install image qrcode pillow
import qrcode
img=qrcode.make("www.zhuanzhuan.com")
img.save("./test.png")
import qrcode
qr = qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=1
)
qr.add_data("https://blog.csdn.net/caidewei121/")
qr.make(fit=True)
img = qr.make_image()
img.save("my_blog.png")
import qrcode
from PIL import Image
url="www.zhuanzhuan.com"
qr=qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=8,
border=2
)
qr.add_data(url)
qr.make(fit=True)
img=qr.make_image()
img=img.convert("RGBA")
icon=Image.open("ABLOGO.png").convert("RGBA")
img_w,img_h=img.size
factor=4
size_w=int(img_w/factor)
size_h=int(img_h/factor)
icon_w,icon_h=icon.size
if icon_w>size_w:
icon_w=size_w
if icon_h>size_h:
icon_h=size_h
icon=icon.resize((icon_w,icon_h),Image.ANTIALIAS)
w=int((img_w-icon_w)/2)
h=int((img_h-icon_h)/2)
img.paste(icon,(w,h),icon)
img.save("./test.png")