当前位置:首页 > IT技术 > Web编程 > 正文

Markdown图床任意转换到其他图床或其他上传接口
2022-04-25 23:14:16

免费图床经常自动删除图片,所以这里把全部笔记转到语雀或者其他,本地图片和网络图片均可。

使用方法就是抓取上传的接口然后cookie等然后替换,把XX.MD文件和脚本放在一个文件夹就可以了。

from multiprocessing.spawn import prepare
import re
import sys
from turtle import up
import requests
import os
def md_img_find():
    try:
        post = None
        path=sys.path[0]
        files=os.listdir(path)
        for file in files:
            if not os.path.isdir(file) and ".md" in file: 
                print("当前处理的文件:"+file)  
                with open(file, 'r',encoding='utf-8') as f:
                    post = f.read()
                    matches = re.compile('!\[.*?\]\((.*?)\)|<img.*?src=['"](.*?)['"].*?>').findall(post)     # 匹配md文件中的图片
                    if matches and len(matches) > 0:
                        for sub_match in matches:       # 正则里有个或,所以有分组,需要单独遍历去修改   
                            for match in sub_match:     # 遍历去修改每个图片
                                if match and len(match) > 0:
                                    print("match pic : ", match)
                                    if re.match('((http(s?))|(ftp))://.*', match):  # 判断是不是已经是一个图片的网址
                                        res_url=upload_net(match)
                                        post = post.replace(match, res_url)
                                    else:
                                        res_url=upload_local(match)
                                        print(res_url)
                                        post = post.replace(match, res_url)
                        if post: open(file, 'w',encoding='utf-8').write(post)
    except Exception as e:
        print(e)

def upload(body):
    try:
        headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
            'Cookie':'xx',
            'Referer': 'https://www.yuque.com/x'
        }    
        response = requests.post(url='文件上传接口',headers=headers,files=body)
        pattern = re.compile(r'https(.+?).png')#提取上传成功的接口
        content=response.content.decode()
        return "https"+pattern.findall(content)[0]+".png"
    except Exception as e:
        print(e)

def upload_net(match):
    try:
        ip="127.0.0.1"
        port="7890"
        proxies = {
                "http": "http://"+ip+':'+port,
                "https": "https://"+ip+':'+port
                } 
        body = {
                    'image_file': ("image.jpg", requests.get(match,proxies=proxies).content, 'image/png')
                    # 代理是为了例如sm.sm图床 访问慢
                    }
        return upload(body)
    except Exception as e:
        print(e)

def upload_local(img_name):
	with open(img_name, "rb")as f_abs:# 以2进制方式打开图片
		body = {
			'image_file': ('image.png', f_abs, 'image/png')
			
			}
		return upload(body)
        
if __name__=='__main__':
    md_img_find()

本文摘自 :https://www.cnblogs.com/

开通会员,享受整站包年服务立即开通 >