Python利用HTMLParser与docx实现网页内容转Word文档

不晚
不晚
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍如何使用Python的HTMLParser解析带有HTML标签的网页源码,并结合docx模块将内容保存为Word文档。重点解决了转换过程中图片下载、格式校验及异常处理的问题,提供了完整的代码示例与注意事项,帮助开发者实现从网页到文档的自动化转换。

本文通过具体实例,详细讲解了如何使用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)

如需了解更多Python相关技术,建议查阅本站专题:《Python编码操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。

希望本文提供的解决方案能对您的Python编程实践有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表