首页 > 编程语言 >python-爬虫-使用 tomd 库,将 html 转换为 markdown 文档

python-爬虫-使用 tomd 库,将 html 转换为 markdown 文档

时间:2022-10-28 14:35:37浏览次数:51  
标签:文件 markdown word format python mdTxt html tomd


python-爬虫-使用 tomd 库,将 html 转换为 markdown 文档


编码问题搞死人!注意:写python前要先设置两个位置的编码,一个文件顶部设置文件编码,一个是 import 后设置系统默认编码!!!


tomd 对与非常复杂的结构,还是不能完美处理,但已经很不错了,用了 不到 200 行的代码写的转换器。


tomd 源码地址:https://github.com/gaojiuli/tomd


对于 per 标签的转换说明:
html 中的 per 为与格式化标签,其中的字符串的原始格式将保留,需要注意的是 tomd 只会对 <pre><code>...</code></pre> 这种嵌套进行解析~


完整的转换实例:

# -*- coding: utf-8 -*-
import codecs
import sys


import tomd


reload(sys)
sys.setdefaultencoding('utf8') # 设置默认编码格式为'utf-8'


save_file='/Library/temp/markdown.md'


def run():
html = getHtml()
print html
mdTxt = tomd.Tomd(html).markdown
print 'markdown :{}'.format(mdTxt)
createFile(mdTxt)


def createFile(mdTxt):
print '系统默认编码:{}'.format(sys.getdefaultencoding())
print '准备写入文件:{}'.format(save_file)
#r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
#w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
#a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
f = codecs.open(save_file,'w+','utf-8')
# f.write('###{}\n'.format(url))
f.write(mdTxt)
#f.write(mdTxt)
f.close()
print '写入文件结束:{}'.format(f.name)




def getHtml():
return u'''
<h1>hello word!你好,世界!</h1>
<h2>hello word!你好,世界!</h2>
<h3>hello word!你好,世界!</h3>
<h4>hello word!你好,世界!</h4>
<h5>hello word!你好,世界!</h5>
<h6>hello word!你好,世界!</h6>
<p>paragraph
<a href="https://github.com">link</a>
<img src="https://github.com" class="dsad">img</img>
</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
</ol>
<blockquote>blockquote</blockquote>
<p>
<code>inline code</code>
</p>
<pre><code>block code</code></pre>
<p>
<b>bold</b>
<i>italic</i>
<b>
<i>bold italic</i>
</b>
</p>
<p>code</p>
<pre><code>
/**
* Sroo
* @param pars
* @return
*/
@ServiceMethod
public String CleanSroomWithRPIsNull(NoRpSRoomClearRequet pars){
return String.format("xxxx",ctripMappingCompensate.cleanSroomWithRPIsNull(pars));
}
</code></pre>
'''






run()


标签:文件,markdown,word,format,python,mdTxt,html,tomd
From: https://blog.51cto.com/u_4518216/5804853

相关文章