-
-
Save kbrx93/04c6e32f1adb43667c2aac6f5feace61 to your computer and use it in GitHub Desktop.
将markdown的图片批量下载到本地进行备份
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os | |
import re | |
import urllib.request | |
import ssl | |
ssl._create_default_https_context = ssl._create_unverified_context | |
def save_img(file_allname): | |
try: | |
file = open(file_allname, encoding='utf-8') | |
text = file.read() | |
p = re.compile(r'!\[.*\]\((.+)\)') | |
img_urls = p.findall(text) | |
for index, img_url in enumerate(img_urls): | |
# 获得对应的路径和文件后缀 | |
dir_path = os.path.splitext(file_allname)[0] | |
file_suffix = os.path.splitext(img_url)[1] | |
# 生成对应的文件夹 | |
if not os.path.exists(dir_path): | |
print('文件夹', dir_path, '不存在,重新建立') | |
os.makedirs(dir_path) | |
# 拼接图片名(包含路径) | |
img_urls = '{}{}{}{}'.format(dir_path, os.sep, index, file_suffix) | |
# 下载图片,并保存到文件夹中 | |
urllib.request.urlretrieve(img_url, filename=img_urls) | |
except IOError as e: | |
print('文件操作失败', e) | |
except Exception as e: | |
print('错误 :', e) | |
def save_dir(file_dir): | |
# 1. 判断文件夹是否存在 | |
if not os.path.exists(file_dir): | |
print('文件夹', file_dir, '不存在') | |
return | |
# 2. 存在的话遍历文件夹 | |
if os.path.isfile(file_dir): | |
save_img(file_dir) | |
else: | |
for temp in os.listdir(file_dir): | |
path = os.path.join(file_dir, temp) | |
# 3. 如果是文件夹,递归 | |
if os.path.isdir(path): | |
save_dir(path) | |
# 4. 如果是文件且是md文件,调用save_img方法 | |
elif os.path.isfile(path) and '.md' == os.path.splitext(path)[1]: | |
save_img(path) | |
# 5. 如果是文件且是其它文件,跳过 | |
else: | |
pass | |
if __name__ == '__main__': | |
save_dir('/Users/kbrx93/Desktop/笔记') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment