图片保存到本地并替换markdown中的url地址
为了本地备份随笔内容。
- 用到
requests下载图片和re解析markdown文本
代码如下:
import re
import os
import requests
# markdown文件的路径,绝对路径
markdown_file_path = "C:\\Users\\wuyucun\\Desktop\\1_sim_test\\2_md file\\基于ProDiag的监控视图-LAD篇.md"
# 读取markdown文件内容
with open(markdown_file_path, 'r', encoding='utf-8') as file:
markdown_content = file.read()
# 使用正则表达式匹配所有URL地址
urls = re.findall(r'!\[[^\]]*\]\(([^)]*\.png)\)', markdown_content)
# 存储所有URL地址
url_list = []
for url in urls:
url_list.append(url)
# 下载图片到本地
for url in url_list:
response = requests.get(url)
if response.status_code == 200:
image_name = os.path.basename(url)[:255] # 限制图片名字长度不超过255个字符
image_dir = os.path.join(os.path.dirname(markdown_file_path),"picture_libs")#markdown文件目录同级下名为picture_libs的文件夹
image_path = os.path.join(image_dir,image_name)#带绝对路径带文件名
image_relpath = os.path.relpath(image_path,os.path.dirname(markdown_file_path))#计算相对路径
with open(image_path, 'wb') as file:
file.write(response.content)
print(f"图片 {image_name} 下载成功")
# 替换markdown文件中的URL地址,这里的image_path需要改成相对路径
markdown_content = markdown_content.replace(url, image_relpath)
else:
print(f"图片 {url} 下载失败")
continue
# 将替换后的内容写回markdown文件
with open(markdown_file_path, 'w', encoding='utf-8') as file:
file.write(markdown_content)
print("完成")
已找到为什么在Markdown中本地的url地址打不开的原因:
- 对于本地图片而言,markdown
不支持绝对路径; - 图片或者路径名称中
不要带空格,不然识别不了; 
拓展:
//url语法
[url连接显示名,可省略](url地址,相对或者绝对地址 "url标题,可省略")
//html对应语法
<a href="url地址" title="url标题">url连接显示名</a>

浙公网安备 33010602011771号