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>
'''