国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現將HTML轉換成doc格式文件的方法示例

2020-02-16 10:46:04
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現將HTML轉換成doc格式文件的方法。分享給大家供大家參考,具體如下:

網頁上的一些文章,因為有格式的原因,它們在網頁上的源碼都是帶有html標簽的,用css來進行描述。本文利用HTML Parser 和docx兩個模塊,對網頁進行解析并存儲到word文檔中。轉換出來的格式相對還是有些粗糙,不喜勿噴。話不多說,直接上代碼。

class HTMLClient:  #獲取html網頁源碼  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  #獲取網絡圖片并保存在程序運行目錄下  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的轉換過程中,圖片保存和處理是比較麻煩的事情,因為可能涉及到圖片格式錯誤,因此為了保證圖片正常運行,應當修改圖片添加異常處理流程。

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=[]  #根據標簽頭類型決定標簽內容的格式  def handle_starttag(self, tag, attrs):    #print "Encountered the beginning of a %s tag" % tag    self.title = False    self.isdescription = False    #<h1>標簽說明其中的內容是標題    if re.match(r'h(/d)', tag):      self.title = True    #圖片的處理比較復雜,首先需要找到對應的圖片的url,然后下載并寫入doc中    #下載的圖片格式如果有問題,docx模塊會報錯,因此重新定義異常處理    #圖片名稱需要記錄下來,在文檔保存后要自動刪除    if tag == "img":      if len(attrs) == 0: pass      else:        for (variable, value) in attrs:          if variable == "src":            #此處圖片url類型為[http://url/pic.img!200*200]            #不同網站圖片類型不同,因此當作不同處理            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)            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜兰市| 丁青县| 文成县| 嘉峪关市| 于田县| 甘谷县| 普宁市| 松滋市| 奎屯市| 延吉市| 夏河县| 新民市| 惠安县| 东乡县| 连城县| 凉城县| 和顺县| 镇安县| 浪卡子县| 永仁县| 阳曲县| 涿州市| 萨迦县| 通许县| 阿拉善盟| 文昌市| 任丘市| 常山县| 宝兴县| 冀州市| 滁州市| 剑川县| 榆林市| 澄城县| 沙雅县| 金堂县| 浦城县| 大姚县| 东平县| 昌江| 德庆县|