Python实现将HTML转换成doc格式文件的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现将HTML转换成doc格式文件的方法。分享给大家供大家参考,具体如下:

网页上的一些文章,因为有格式的原因,它们在网页上的源码都是带有html标签的,用css来进行描述。本文利用HTML Parserdocx两个模块,对网页进行解析并存储到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)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python编码操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python pymongo模块常用操作分析

Python pymongo模块常用操作分析

本文实例讲述了Python pymongo模块常用操作。分享给大家供大家参考,具体如下: 环境:pymongo3.0.3,python3 以下是我整理的一些关于pymongo的操作,网上...

python3实现钉钉消息推送的方法示例

背景 偶然发现一个python实现的按照农历/阴历推送消息提醒的程序,钉钉群消息推送。此处总结并对其可推送的消息做。 DingtalkNotice 环境:python3.7 安装:...

Python实现多属性排序的方法

Python实现多属性排序的方法

多属性排序: 把需要排序的属性拿出来作为一个 tuple,主要的放前面,次要的放后面。 假如某对象有n个属性,那么先按某规则对属性a进行排序,在属性a相等的情况下再按某规则对属性b进行排...

Python multiprocessing多进程原理与应用示例

本文实例讲述了Python multiprocessing多进程原理与应用。分享给大家供大家参考,具体如下: multiprocessing包是Python中的多进程管理包,可以利用mu...

Python实现统计文本文件字数的方法

本文实例讲述了Python实现统计文本文件字数的方法。分享给大家供大家参考,具体如下: 统计文本文件的字数,从当前目录下的file.txt取文件 # -*- coding: GBK...