Using Python to Parse Images in Markdown Documents and Save Them Locally~
Background A while ago Jianshu seemed to be going under, which made me a bit panicked, since most of my blogs are hosted on Jianshu. Although Jianshu provides a package export feature, it can only export text—images still live on Jianshu's servers. Plus I've always wanted to rebuild a personal blog, so this article came about. Approach First I need to parse the markdown documents, then get all the images in them, and save the images into directories organized by md file. Parsing markdown documents Here I used the misaka module, which is said to be python's mar
目录11 个章节
Background
A while ago Jianshu seemed to be going under, which made me a bit panicked, since most of my blogs are hosted on Jianshu. Although Jianshu provides a package export feature, it can only export text—images still live on Jianshu's servers. Plus I've always wanted to rebuild a personal blog, so this article came about.
Approach
First I need to parse the markdown documents, then get all the images in them, and save the images into directories organized by md file.
Parsing markdown documents
Here I used the misaka module, which is said to have the best performance among Python markdown parsers. But its documentation is really sparse—too little content, and it's written unclearly. Its basic function seems to be parsing markdown documents into HTML documents, but it doesn't seem to have methods for directly operating on markdown elements.
No problem, I can parse the HTML the way I usually write crawlers, so I can get the images in a roundabout way~ I'll use BeautifulSoup here
Downloading images
Very simple, just requests, nothing much to say.
Implementation
Traversing files
First I need to traverse all md documents in the folder:
def get_files_list(dir):
"""
获取一个目录下所有文件列表,包括子目录
:param dir:
:return:
"""
files_list = []
for root, dirs, files in os.walk(dir, topdown=False):
for file in files:
files_list.append(os.path.join(root, file))
return files_list
Parsing md documents and getting all images
First convert markdown to HTML with misaka, then extract all img tags.
def get_pics_list(md_content):
"""
获取一个markdown文档里的所有图片链接
:param md_content:
:return:
"""
md_render = misaka.Markdown(misaka.HtmlRenderer())
html = md_render(md_content)
soup = BeautifulSoup(html, features='html.parser')
pics_list = []
for img in soup.find_all('img'):
pics_list.append(img.get('src'))
return pics_list
Downloading images
def download_pics(url, file):
img_data = requests.get(url).content
filename = os.path.basename(file)
dirname = os.path.dirname(file)
targer_dir = os.path.join(dirname, f'{filename}.assets')
if not os.path.exists(targer_dir):
os.mkdir(targer_dir)
with open(os.path.join(targer_dir, f'{uuid.uuid4().hex}.jpg'), 'w+') as f:
f.buffer.write(img_data)
Complete code
The complete code for this project has been uploaded to GitHub, at the following address: https://github.com/Deali-Axy/Markdown-Image-Parser
Running
pip install -r requirements.txt
python spider.py
Welcome to connect with me
- Coding livestream: https://live.bilibili.com/11883038
- WeChat official account: DealiAxy
- Zhihu: https://www.zhihu.com/people/dealiaxy
- Blog: https://blog.deali.cn
- Jianshu: https://www.jianshu.com/u/965b95853b9f
_EOF_
Using Python to Parse Images in Markdown Documents and Save Them Locally~
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
现代 Python 程序优雅处理日期时间的避坑指南
Python 时间处理还是得踩坑?`datetime`、`time`、`calendar` 搞得人头大,Naive vs Aware 时区陷阱更是坑爹。2026 年了还用 `pytz`?标准库 `ZoneInfo` 加上 `Pendulum`、`Arrow` 才叫现代化,至少不用再写反人类的时间字符串解析。数据库存 UTC,前端传 ISO 8601,简单点行不行?
2026-03-25 · Python · 约 1 分钟
Python接入企业微信推送信息到内部群里
前言 之前一篇文章提到了使用wechatpy库来实现企业微信应用登录:Django + Taro 前后端分离项目实现企业微信登录 其实这个库可以实现的功能非常多,基本微信开发涉及到的功能都能实现。 本文介绍一个很常用的场景:实时推送信息到企业微信群里。 安装 首先安装wechatpy库 pip install wechatpy 如果运行的时候提示需要安装其他库(比如加解密相关的)那就按照提示安装,
2022-04-08 · Python · 约 1 分钟
升级pip之后连pip都不能用了?简单解决方法
前言 最近在服务器上部署项目的时候,用pip安装库,结果提示可以升级,那我就按照提示升级了pip,结果pip就用不了了。 错误信息如下: Traceback (most recent call last): File /usr/bin/pip3, line 9, in module from pip import main ImportError: cannot import name
2021-12-18 · Python · 约 1 分钟
Python数据展示 - 生成表格图片
前言 前一篇文章介绍了推送信息到企业微信群里,其中一个项目推送的信息是使用Python自动生成的表格,本文来讲讲如何用Python生成表格图片。 选一个合适库 Python最大的优点就是第三方库丰富,基本你要什么功能,都能找到别人实现好的库,几行代码一调用就完事了。 Pytable 项目地址:https://github.com/HiroshiARAKI/pytable 最先找到的是日本人开发的p
2022-04-09 · Python · 约 1 分钟
讨论
共 0 条加载评论中…