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

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

python 复制代码
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'<img.*?src="(.*?)".*?>', 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)
相关推荐
lpfasd12329 分钟前
系统、详细地介绍 GitHub 官方 API 的能力边界
github
KevinShi_BJ41 分钟前
Github Copilot 实践
github·copilot
秋雨雁南飞1 小时前
图床软件 PicGo + Github
github·picgo·图床
moment&forever2 小时前
GitHub 托管 API 地址配置文件:实现零成本云配置托管
github
小龙13 小时前
【Git 报错解决】本地无有效提交无法推送(`src refspec main does not match any`)
git·github·报错
行百里er17 小时前
一个还没写代码的开源项目,我先来“画个饼”:Spring Insight
后端·开源·github
知行力18 小时前
【GitHub每日速递 20260108】告别云服务弊端,Memos隐私至上自托管笔记服务来袭!
笔记·github
无限进步_19 小时前
【数据结构&C语言】对称二叉树的递归之美:镜像世界的探索
c语言·开发语言·数据结构·c++·算法·github·visual studio
CoderJia程序员甲20 小时前
GitHub 热榜项目 - 日榜(2026-1-7)
人工智能·ai·大模型·github·ai教程
逛逛GitHub20 小时前
GitHub 上 2300 点赞的搜索 Agent,有点惊艳啊。
github