前言

描述

有时写Markdown会把图片放在图床,而且图床上传图片后会改变图片的名称,想要下载下来备份并不是很方便,不如写个程序自动保存一下,以后不想用图床了还可以把图片直接放在自己的服务器,这时只需要批量对图片地址进行替换。

举例

像这样,我使用了hello图床

hello图床(https://www.helloimg.com/)

但是当我像把图片放到服务器上,不再用图床了,就得这样改

即将https://www.helloimg.com/images/2021/02/10替换成/static/post

前提是图片名称和在图床上一样

那么如何保持一样?直接从图床上下载图片就好

这个程序就是替你完成这个工作

开始

程序

Python3程序

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
'''
Author: lx56
Blog: https://blog.lxscloud.top
'''
import time
import requests
import os

mddir = './md/' #设置根路径
dldir = './dl/'
markdown_setup = ["![", "](", ")"]
download_list = ["https://", "http://"]
ext_name = ["md"]
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}

def checkdir_andcreate(dir_path_set):
if dir_path_set[-1:] == "":
dir_path_set = dir_path_set[0:-1]
if os.path.isdir(dir_path_set) == False:
os.mkdir(dir_path_set)


def file_size_trans(filesize_input_B):
precent_unit = ''
# KB
if 1024 <= filesize_input_B < (1024 ** 2):
precent_unit = 'KB'
filesize_input_B = filesize_input_B / 1024
# MB
elif (1024 ** 2) <= filesize_input_B < (1024 ** 3):
precent_unit = 'MB'
filesize_input_B = filesize_input_B / (1024 ** 2)
# GB
elif (1024 ** 3) <= filesize_input_B < (1024 ** 4):
precent_unit = 'GB'
filesize_input_B = filesize_input_B / (1024 ** 3)
# TB
elif (1024 ** 4) <= filesize_input_B < (1024 ** 5):
precent_unit = 'TB'
filesize_input_B = filesize_input_B / (1024 ** 4)
# B
else:
precent_unit = 'Byte'
r_info = "{:.1f}".format(filesize_input_B) + ' ' + precent_unit
return r_info

def download_file_with_speed(download_url, dirset = "."):
dirset += "/"

filepath = dirset + download_url[download_url.rindex("/")+1:]
if os.path.isfile(filepath):
print("File exists, skip....")
return
# 流式请求下载地址并以下载名保存文件
with requests.get(download_url, stream=True, headers=headers) as r, open(filepath, 'wb') as file:
# 获得文件的大小,单位字节B
total_size = int(r.headers['content-length'])
# 已下载的字节大小
content_size = 0
# 进度下载完成的百分比
process_p = 0
# 记录开始时间
start_time = time.time()
# 到上一秒的下载的文件大小
temp_size = 0
# 开始下载每次请求1024字节
for content in r.iter_content(chunk_size=1024):
file.write(content)
# 更新下载大小
content_size += len(content)
# 计算下载进度
process_p = (content_size / total_size) * 100
# 每一秒统计一次下载量
if time.time() - start_time > 1:
# 重置开始时间
start_time = time.time()
# 每秒的下载量
speed = content_size - temp_size
print('Process: {:.1f}% Speed: {}/S'.format(process_p, file_size_trans(speed)))
# 重置以下载大小
temp_size = content_size

print('100% Size: {}'.format(file_size_trans(total_size)))


def check_mark(str_line, list_check, mode_check):
resault_check = False
for i in list_check:
if mode_check == True:
resault_check = True
try:
str_line.index(i)
except:
resault_check = False
break
elif mode_check == False:
resault_check = False
state = 0
try:
str_line.index(i)
state = 1
except:
state = 0
if state == 1:
resault_check = True
break
else:
resault_check = False
return resault_check

def read_and_find(file_name):
f1_n = file_name
dir_set = dldir + f1_n[f1_n.rindex("/")+1:f1_n.rindex(".")]
try:
if os.path.isdir(dir_set) == False:
os.mkdir(dir_set)
dir_set_ok = True
except:
print("Dir create fail")
dir_set_ok = False
if dir_set_ok:
try:
file_processing = open(file_name, 'r', encoding = 'utf-8')
for line in file_processing.readlines():
lines = str(line)
if check_mark(lines, markdown_setup, True) == True:
http_l = lines.index("](") + 2
http_r = lines.index(")", http_l)
pic_http_addr = lines[http_l:http_r]

if check_mark(pic_http_addr,download_list , False):
print("Try to download:", pic_http_addr)
#下载文件
try:
download_file_with_speed(pic_http_addr, dir_set)
print()
except Exception as e:
print("Err download:", pic_http_addr, f"err={e}")
print()
file_processing.close()
return True
except:
print("Err at read file :", file_name)
return False

checkdir_andcreate(dldir)
checkdir_andcreate(mddir)

dict_pic_path = []
list = os.listdir(mddir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(mddir,list[i])
if os.path.isfile(path):
str_path = str(path)
str_path = str_path[str_path.rfind(".")+1:]
for i in ext_name: #忽略不在白名单的扩展名
if str_path == i:
#print(path)
dict_pic_path.append(path)
break

for i in dict_pic_path:
print("File:", i)
print("-----------------------------------")
read_and_find(i)
print("-----------------------------------\n")

运行

初次运行会产生md和dl文件夹

请将目标markdown文件放入md文件夹

然后再次运行程序,即可在dl文件夹看到下载的图片

状况

运行后报错可能是因为

缺少必要库requests

1
pip3 install requests

使用的是python2.7

请使用python3解释器运行

1
python3

Dir create fail

程序可能没有创建目录的权限或目录不可写

Err at read file

无法读取markdown文件,可能是没有读取权限

Err download

下载错误,图片不存在或网络不通

结束

谢谢观看

EOF