背景
前陣子簡書好像說是涼了,搞得我有點小慌,畢竟我的大部分博客都是放在簡書上面的,雖然簡書提供了打包導出功能,但是只能導出文字,圖片的話還是存在簡書服務器上面,再加上我一直想要重新做一個個人博客,於是就有了這篇文章。
思路
首先是要解析markdown文檔,然后獲取到其中的所有圖片,再把圖片按md文件分好目錄保存。
解析markdown文檔
這里我用了misaka模塊,據說是python的markdown解析器里性能最好的,不過這個的文檔着實是精簡,太少內容了,寫得不清不楚的,基本功能看來就是把markdown文檔解析為html文檔,但是好像沒有直接操作markdown元素的方法。
沒事,我可以像平時寫爬蟲那樣解析html呀,不就曲線救國拿到圖片了嗎~
這里就用BeautifulSoup啦
下載圖片
很簡單,就是requests,沒啥好說的。
實現
遍歷文件
首先要遍歷文件夾里面的所有md文檔:
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
解析md文檔 獲取所有圖片
先用misaka把markdown轉換成html,然后再拿出所有img。
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
下載圖片
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)
完整代碼
本項目的完整代碼已經上傳到GitHub了,地址如下:
https://github.com/Deali-Axy/Markdown-Image-Parser
運行
pip install -r requirements.txt
python spider.py
歡迎與我交流
- 打代碼直播間:https://live.bilibili.com/11883038
- 微信公眾號:DealiAxy
- 知乎:https://www.zhihu.com/people/dealiaxy
- 博客:https://blog.deali.cn