本脚本旨获取指定文件中在网络中所有的图片,并存储在本地,并且修改文件中的url指向本地图片。
import re
import requests
import time
ua = 自己去浏览器寻找
headers = {"User-Agent": ua}
file_dir = r'F:\md笔记\java\JVM\\'
file_n = 'test'
file_suffix = '.md'
fileName = file_dir+file_n+file_suffix
img_tsrc = 'assets/'
img_src = file_dir + img_tsrc
with open(file=fileName, mode="r", encoding='utf-8') as f1:
s_count = 0
fail_count = 0
sus_count = 0
lines = f1.readlines()
for i in range(0, len(lines)):
url = re.findall('<img src="(.*?)"', lines[i], re.S)
if len(url)!=0:
url = url[0]
if len(re.findall(img_tsrc+'.*', url, re.S))!=0:
print('第',i,'行:为本地图片')
s_count+=1
continue
timestamp = int(time.time())
image_name = str(time.strftime('%Y%m%d%H%M%S', time.localtime(timestamp)))+str(i)+".png"
img = requests.get(url,headers=headers)
if img.status_code != 200:
print('第',i,'行:','!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!',img.status_code)
fail_count+=1
continue
target = open(img_src+image_name,'ab')
target.write(img.content)
target.close()
lines[i] = lines[i].replace(url,img_tsrc+image_name)
print('第',i,'行:',url+'成功转为'+img_tsrc+image_name)
sus_count+=1
print('---本地图片为:',s_count,'个---')
print('---获取失败为:',fail_count,'个---')
print('---转化成功为:',sus_count,'个---')
fileName2 = file_dir+file_n+'-修改'+file_suffix
with open(file = fileName2,mode='w',encoding='utf-8') as f2:
f2.writelines(lines)
控制台输出: 报感叹号的表示转化失败,后面是获取图片的状态码;为本地图片的说明不需要转化。
转化成功的效果:
|