使用Python將HTML文檔轉換爲Markdown文檔

前言

個人我的博客是Hexo+Next搭建的,風格我很喜歡,也不打算更換。最近可能電腦很差使了,兩次重裝系統,每次都要從新搭建博客,搭建速度也很快,可是依然有個困擾個人問題,那就是電腦卡死的時候有些博客沒有備份,只有上傳到Github生成的html文檔。今天發現個有趣的python庫,能夠將html轉換回markdown,試驗了一下效果還不錯。html

代碼

下面先上代碼:python

#Author:Sun Yan
#Function: convert html to md

import html2text as ht  # pip install html2text
import os 
text_maker = ht.HTML2Text()
#text_maker.ignore_links = True
text_maker.bypass_tables = False
path ="C:\\Users\\14050\\Desktop\\code\\1.html"
htmlfile = open(path,'r',encoding='UTF-8')
htmlpage = htmlfile.read()
text = text_maker.handle(htmlpage)
md = text.split('#')  # split post content
open("1.md","w").write(md[1])  # write file as a md file

說明

安裝庫

在個人電腦上直接pip安裝沒有成功,我是在pypi上下載以後安裝的 html2textmarkdown

使用

使用也比較簡單,注意兩個地方便可:post

  1. 忽略連接和表格

我這裏是按照官方文檔中寫的,實際測試連接能夠不忽略,表格沒有測試。測試

2.#的做用code

在這裏使用#號來分割文章的核心內容,捨棄博客的header和footer。htm

相關文章
相關標籤/搜索