返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Python

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

曦远 (DealiAxy)约 8 分钟
目录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

_EOF_

Using Python to Parse Images in Markdown Documents and Save Them Locally~

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

自己动手开发简单消息队列(异步任务队列):Python实现

又是造轮子系列咯,Python上有很多成熟完善的异步任务队列框架可以用,比如Celery,或者RQ,不过这些都不自带消息队列服务,都需要使用Redis、RabbitMQ之类的消息队列才行,我用到小项目中又不需要附带这么多东西,于是自己动手来实现咯。 思路 将需要异步执行的任务添加到队列 自动从队列中取出任务,创建新线程执行 保存任务的执行结果和输出 任务完成,调用回调函数,处理返回的数据 使用输出

2021-12-18 · Python · 约 1 分钟

关于Python的异常处理

前言 异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。 Python 中(至少)有两种错误:语法错误和异常( syntax errors 和 exceptions )。下面稍微介

2022-05-27 · Python · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…