Python實(shí)現(xiàn)將HTML轉(zhuǎn)換成doc格式文件的方法示例
本文實(shí)例講述了Python實(shí)現(xiàn)將HTML轉(zhuǎn)換成doc格式文件的方法。分享給大家供大家參考,具體如下:
網(wǎng)頁上的一些文章,因?yàn)橛懈袷降脑?,它們?cè)诰W(wǎng)頁上的源碼都是帶有html標(biāo)簽的,用css來進(jìn)行描述。本文利用HTML Parser 和docx兩個(gè)模塊,對(duì)網(wǎng)頁進(jìn)行解析并存儲(chǔ)到word文檔中。轉(zhuǎn)換出來的格式相對(duì)還是有些粗糙,不喜勿噴。話不多說,直接上代碼。
class HTMLClient:
#獲取html網(wǎng)頁源碼
def GetPage(self, url):
#user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
user_agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36'
headers = { 'User-Agent' : user_agent }
req = urllib.request.Request(url, None, headers)
try:
res = urllib.request.urlopen(req)
return res.read().decode("utf-8")
except urllib.error.HTTPError as e:
return None
#獲取網(wǎng)絡(luò)圖片并保存在程序運(yùn)行目錄下
def GetPic(self, url):
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
req = urllib.request.Request(url, None, headers)
try:
res = urllib.request.urlopen(req)
return res.read()
except urllib.error.HTTPError as e:
return None
html到doc的轉(zhuǎn)換過程中,圖片保存和處理是比較麻煩的事情,因?yàn)榭赡苌婕暗綀D片格式錯(cuò)誤,因此為了保證圖片正常運(yùn)行,應(yīng)當(dāng)修改圖片添加異常處理流程。
class MYHTMLParser(HTMLParser):
def __init__(self, docfile):
HTMLParser.__init__(self)
self.docfile = docfile
self.doc = Document(docfile)
self.myclient = HTMLClient()
self.text = ''
self.title = False
self.isdescription = False
self.picList=[]
#根據(jù)標(biāo)簽頭類型決定標(biāo)簽內(nèi)容的格式
def handle_starttag(self, tag, attrs):
#print "Encountered the beginning of a %s tag" % tag
self.title = False
self.isdescription = False
#<h1>標(biāo)簽說明其中的內(nèi)容是標(biāo)題
if re.match(r'h(\d)', tag):
self.title = True
#圖片的處理比較復(fù)雜,首先需要找到對(duì)應(yīng)的圖片的url,然后下載并寫入doc中
#下載的圖片格式如果有問題,docx模塊會(huì)報(bào)錯(cuò),因此重新定義異常處理
#圖片名稱需要記錄下來,在文檔保存后要自動(dòng)刪除
if tag == "img":
if len(attrs) == 0: pass
else:
for (variable, value) in attrs:
if variable == "src":
#此處圖片url類型為[http://url/pic.img!200*200]
#不同網(wǎng)站圖片類型不同,因此當(dāng)作不同處理
picdata = self.myclient.GetPic(value.split('!')[0])
if picdata == None:
pass
else:
pictmp = value.split('/')[-1].split('!')[0]
picfix = value.split('/')[-1].split('!')[-1]
with open(pictmp, 'wb') as pic:
pic.write(bytes(picdata))
pic.close()
try:
if picfix[0:1] == 'c':
self.doc.add_picture(pictmp, width=Inches(4.5))
else:
self.doc.add_picture(pictmp)#, width=Inches(2.25))
except docx.image.exceptions.UnexpectedEndOfFileError as e:
print(e)
self.picList.append(pictmp)
#javascript腳本
if tag == 'script':
self.isdescription = True
def handle_data(self, data):
if self.title == True:
if self.text != '':
self.doc.add_paragraph(self.text)
self.text = ''
self.doc.add_heading(data, level=2)
if self.isdescription == False:
self.text += data
def handle_endtag(self, tag):
#if tag == 'br' or tag == 'p' or tag == 'div':
if self.text != '':
self.doc.add_paragraph(self.text)
self.text = ''
def complete(self, html):
self.feed(html)
self.doc.save(self.docfile)
for item in self.picList:
if os.path.exists(item):
os.remove(item)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python設(shè)計(jì)模式之觀察者模式實(shí)例
這篇文章主要介紹了設(shè)計(jì)模式中的觀察者模式Python實(shí)例,需要的朋友可以參考下2014-04-04
Python自動(dòng)化構(gòu)建工具scons使用入門筆記
這篇文章主要介紹了Python自動(dòng)化構(gòu)建工具scons使用入門筆記,本文講解了安裝scons、scons常用命令、scons使用示例等內(nèi)容,需要的朋友可以參考下2015-03-03
Python解析json文件相關(guān)知識(shí)學(xué)習(xí)
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式。接下來通過本文給大家介紹python解析json文件相關(guān)知識(shí),對(duì)python解析json文件相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-03-03
Python學(xué)習(xí)之時(shí)間包使用教程詳解
本文主要介紹了Python中的內(nèi)置時(shí)間包:datetime包?與?time包?,通過學(xué)習(xí)時(shí)間包可以讓我們的開發(fā)過程中對(duì)時(shí)間進(jìn)行輕松的處理,快來跟隨小編一起學(xué)習(xí)一下吧2022-03-03
python應(yīng)用Axes3D繪圖(批量梯度下降算法)
這篇文章主要為大家詳細(xì)介紹了python應(yīng)用Axes3D繪圖,批量梯度下降算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
Python使用pycharm導(dǎo)入pymysql教程
這篇文章主要介紹了Python使用pycharm導(dǎo)入pymysql教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-09-09

