markdown文件中的外链图片上传到GitHub图床

markdown文件中的外链图片上传到GitHub图床

import os
import re
import requests
from github import Github


# 获取GitHub令牌和图床存储库信息
TOKEN = ""
REPO_NAME = "" # 仓库名:如img-bed
REPO_OWNER = "" # 拥有者名称:如yijunquan

# 创建PyGithub对象
g = Github(TOKEN)
repo = g.get_user(REPO_OWNER).get_repo(REPO_NAME)

# 指定目录路径
path = "."

# 获取目录下所有文件的名称
file_names = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
# 打印输出所有文件的名称
for name in file_names:
    if ".md" not in name:
        continue
    if path == '.':
        file = name
    else:
        file = path + name

    print("文件: " + file)
    # 读取Markdown文件
    with open(file, "r", encoding='utf-8') as f:
        content = f.read()

    # 查找Markdown文件中的所有图片标签
    img_tags = re.findall(r"!\[.*?\]\((.*?)\)", content) + re.findall(r'', content)


    # 遍历每个图片标签,上传到GitHub图床并替换Markdown文件中的链接
    for img_tag in img_tags:

        print(img_tag)
        if "https://raw.githubusercontent.com" in img_tag:
            print("跳过")
            continue
        # 获取图片URL
        img_url = img_tag

        # 下载图片数据
        response = requests.get(img_url)
        img_data = response.content

        # 上传图片到GitHub图床
        img_name = os.path.basename(img_url)
        if img_name[0:3] == "%20":
            img_name = img_name[3:]
        img_path = f"img13/{img_name}"
        img_file = repo.create_file(img_path, f"Upload image {img_name}", img_data)
        img_url = "https://raw.githubusercontent.com/yijunquan-afk/img-bed-1/main/" + img_path
        print("替换为:"+ img_url)
        # 替换Markdown文件中的链接
        content = content.replace(img_tag, img_url)

    # 更新Markdown文件
    with open(file, "w", encoding='utf-8') as f:
        f.write(content)

你可能感兴趣的:(脚本,github)