markdown文件中的外链图片上传到GitHub图床
import os
import re
import requests
from github import Github
TOKEN = ""
REPO_NAME = ""
REPO_OWNER = ""
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)
with open(file, "r", encoding='utf-8') as f:
content = f.read()
img_tags = re.findall(r"!\[.*?\]\((.*?)\)", content) + re.findall(r'', content)
for img_tag in img_tags:
print(img_tag)
if "https://raw.githubusercontent.com" in img_tag:
print("跳过")
continue
img_url = img_tag
response = requests.get(img_url)
img_data = response.content
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)
content = content.replace(img_tag, img_url)
with open(file, "w", encoding='utf-8') as f:
f.write(content)

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66