【Python】HTML中Base64存储的图片转为本地图片文件

我用jupyter notebook写了笔记之后,想导出markdown,然后导出不了,我就只能导出html,结果导出的html存储图片用的base64的方式……
于是我就要把导出的html文档里面的base64格式的图片保存为本地图片

# -*- coding: UTF-8 -*-
# 开发人员:萌狼蓝天
# 博客:Https://mllt.cc
# 笔记:Https://cnblogs.com/mllt
# 哔哩哔哩/微信公众号:萌狼蓝天
# 开发时间:2022/8/21
import base64
import io
import os

import bs4


def base64ToImage(name,base64res):
    res = base64res.split(",")[1]
    img_base64_decode = base64.b64decode(res)
    # image = io.BytesIO(img_base64_decode)
    # print(image)
    # 输出文件夹是否存在
    if not os.path.exists("out"):
        os.makedirs("out")
        print("文件夹创建成功")
    # 输出图片
    url = r'out\img_' + name + '.png'
    with open(url, 'wb') as img:
        img.write(img_base64_decode)
    with open("img_url.txt","a+",encoding="utf8") as file:
        text ='[imags](' + url + ')'
        file.write("%s\n\n" % (text))
    
if __name__ == '__main__':
    filePath = r"萌狼学习笔记02_神经网络优化.html"
    soup = bs4.BeautifulSoup(open(filePath,encoding='utf-8'),features='html.parser')
    i=0
    for img in soup.find_all("img"):
        i+=1
        base64ToImage("图片"+str(i),img.get("src"))
    print("完成,生成图片",i,"张")

猜你喜欢

转载自blog.csdn.net/ks2686/article/details/127285557