Python实现批量将word转html并将html内容发布至网站的方法


Posted in Python onJuly 14, 2015

本文实例讲述了Python实现批量将word转html并将html内容发布至网站的方法。分享给大家供大家参考。具体实现方法如下:

#coding=utf-8
__author__ = 'zhm'
from win32com import client as wc
import os
import time
import random
import MySQLdb
import re
def wordsToHtml(dir):
#批量把文件夹的word文档转换成html文件
 #金山WPS调用,抢先版的用KWPS,正式版WPS
 word = wc.Dispatch('KWPS.Application')
 for path, subdirs, files in os.walk(dir):
  for wordFile in files:
   wordFullName = os.path.join(path, wordFile)
   #print "word:" + wordFullName
   doc = word.Documents.Open(wordFullName)
   wordFile2 = unicode(wordFile, "gbk")
   dotIndex = wordFile2.rfind(".")
   if(dotIndex == -1):
    print '********************ERROR: 未取得后缀名!'
   fileSuffix = wordFile2[(dotIndex + 1) : ]
   if(fileSuffix == "doc" or fileSuffix == "docx"):
    fileName = wordFile2[ : dotIndex]
    htmlName = fileName + ".html"
    htmlFullName = os.path.join(unicode(path, "gbk"), htmlName)
    # htmlFullName = unicode(path, "gbk") + "\\" + htmlName
    print u'生成了html文件:' + htmlFullName
    doc.SaveAs(htmlFullName, 8)
    doc.Close()
 word.Quit()
 print ""
 print "Finished!"
def html_add_to_db(dir):
#将转换成功的html文件批量插入数据库中。
 conn = MySQLdb.connect(
  host='localhost',
  port=3306,
  user='root',
  passwd='root',
  db='test',
  charset='utf8'
  )
 cur = conn.cursor()
 for path, subdirs, files in os.walk(dir):
  for htmlFile in files:
   htmlFullName = os.path.join(path, htmlFile)
   title = os.path.splitext(htmlFile)[0]
   targetDir = 'D:/files/htmls/'
   #D:/files为web服务器配置的静态目录
   sconds = time.time()
   msconds = sconds * 1000
   targetFile = os.path.join(targetDir, str(int(msconds))+str(random.randint(100, 10000)) +'.html')
   htmlFile2 = unicode(htmlFile, "gbk")
   dotIndex = htmlFile2.rfind(".")
   if(dotIndex == -1):
    print '********************ERROR: 未取得后缀名!'
   fileSuffix = htmlFile2[(dotIndex + 1) : ]
   if(fileSuffix == "htm" or fileSuffix == "html"):
    if not os.path.exists(targetDir):
     os.makedirs(targetDir)
    htmlFullName = os.path.join(unicode(path, "gbk"), htmlFullName)
    htFile = open(htmlFullName,'rb')
    #获取网页内容
    htmStrCotent = htFile.read()
    #找出里面的图片
    img=re.compile(r"""<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>""",re.I)
    m = img.findall(htmStrCotent)
    for tagContent in m:
     imgSrc = unicode(tagContent, "gbk")
     imgSrcFullName = os.path.join(path, imgSrc)
     #上传图片
     imgTarget = 'D:/files/images/whzx/'
     img_sconds = time.time()
     img_msconds = sconds * 1000
     targetImgFile = os.path.join(imgTarget, str(int(img_msconds))+str(random.randint(100, 10000)) +'.png')
     if not os.path.exists(imgTarget):
      os.makedirs(imgTarget)
     if not os.path.exists(targetImgFile) or(os.path.exists(targetImgFile) and (os.path.getsize(targetImgFile) != os.path.getsize(imgSrcFullName))):
      tmpImgFile = open(imgSrcFullName,'rb')
      tmpWriteImgFile = open(targetImgFile, "wb")
      tmpWriteImgFile.write(tmpImgFile.read())
      tmpImgFile.close()
      tmpWriteImgFile.close()
      htmStrCotent=htmStrCotent.replace(tagContent,targetImgFile.split(":")[1])
    if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(htmlFullName))):
     #用iframe包装转换好的html文件。
     iframeHtml='''
     <script type="text/javascript" language="javascript">
      function iFrameHeight() {
       var ifm= document.getElementById("iframepage");
       var subWeb = document.frames ? document.frames["iframepage"].document:ifm.contentDocument;
       if(ifm != null && subWeb != null) {
        ifm.height = subWeb.body.scrollHeight;
       }
      }
     </script>
     <iframe src='''+targetFile.split(':')[1]+'''
      marginheight="0" marginwidth="0" frameborder="0" scrolling="no" width="765" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()" ></iframe>
     '''
     tmpTargetFile = open(targetFile, "wb")
     tmpTargetFile.write(htmStrCotent)
     tmpTargetFile.close()
     htFile.close()
     try:
      # 执行
      sql = "insert into common_article(title,content) values(%s,%s)"
      param = (unicode(title, "gbk"),iframeHtml)
      cur.execute(sql,param)
     except:
      print "Error: unable to insert data"
 cur.close()
 conn.commit()
 # 关闭数据库连接
 conn.close()
if __name__ == '__main__':
 wordsToHtml('d:/word')
 html_add_to_db('d:/word')

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

Python 相关文章推荐
sqlalchemy对象转dict的示例
Apr 22 Python
django+js+ajax实现刷新页面的方法
May 22 Python
Pandas:Series和DataFrame删除指定轴上数据的方法
Nov 10 Python
python程序封装为win32服务的方法
Mar 07 Python
Python一行代码解决矩阵旋转的问题
Nov 30 Python
CentOS7下安装python3.6.8的教程详解
Jan 03 Python
Python制作简易版小工具之计算天数的实现思路
Feb 13 Python
python在不同条件下的输入与输出
Feb 13 Python
Python3.x+pyqtgraph实现数据可视化教程
Mar 14 Python
Python venv虚拟环境配置过程解析
Jul 08 Python
Python如何操作docker redis过程解析
Aug 10 Python
Python字符串的15个基本操作(小结)
Feb 03 Python
Python删除windows垃圾文件的方法
Jul 14 #Python
Python简单计算文件夹大小的方法
Jul 14 #Python
Python判断直线和矩形是否相交的方法
Jul 14 #Python
Python下Fabric的简单部署方法
Jul 14 #Python
python简单获取数组元素个数的方法
Jul 13 #Python
python连接字符串的方法小结
Jul 13 #Python
简单上手Python中装饰器的使用
Jul 12 #Python
You might like
PHP个人网站架设连环讲(二)
2006/10/09 PHP
php模板中出现空行解决方法
2011/03/08 PHP
PHP crypt()函数的用法讲解
2019/02/15 PHP
Jquery+ajax请求data显示在GridView上(asp.net)
2010/08/27 Javascript
动感效果的TAB选项卡jquery 插件
2011/07/09 Javascript
Javascript闭包用法实例分析
2015/01/23 Javascript
简介JavaScript中toTimeString()方法的使用
2015/06/12 Javascript
原生js实现百叶窗效果及原理介绍
2016/04/12 Javascript
JavaScript类型系统之布尔Boolean类型详解
2016/06/26 Javascript
最丑的时钟效果!js canvas时钟制作方法
2016/08/15 Javascript
JS实现二叉查找树的建立以及一些遍历方法实现
2017/04/17 Javascript
详解JavaScript数组过滤相同元素的5种方法
2017/05/23 Javascript
vue实现pdf导出解决生成canvas模糊等问题(推荐)
2018/10/18 Javascript
JS中的算法与数据结构之字典(Dictionary)实例详解
2019/08/20 Javascript
layer.js open 隐藏滚动条的例子
2019/09/05 Javascript
快速解决Vue、element-ui的resetFields()方法重置表单无效的问题
2020/08/12 Javascript
python访问sqlserver示例
2014/02/10 Python
Python设计模式之MVC模式简单示例
2018/01/10 Python
Python实现的大数据分析操作系统日志功能示例
2019/02/11 Python
使用Python在Windows下获取USB PID&amp;VID的方法
2019/07/02 Python
Django 静态文件配置过程详解
2019/07/23 Python
解决python gdal投影坐标系转换的问题
2020/01/17 Python
Python实现的北京积分落户数据分析示例
2020/03/27 Python
纯CSS3打造动感漂亮时尚的扇形菜单
2014/03/18 HTML / CSS
html5教程调用绘图api画简单的圆形代码分享
2013/12/04 HTML / CSS
成人教育自我鉴定
2013/11/01 职场文书
企业消防安全制度
2014/02/02 职场文书
我们的节日端午节活动方案
2014/03/02 职场文书
文体活动总结范文
2014/05/05 职场文书
送温暖献爱心活动总结
2014/07/08 职场文书
国际语言毕业生求职信
2014/07/08 职场文书
小学生感恩父母演讲稿
2014/08/28 职场文书
房屋所有权证明
2014/10/20 职场文书
事业单位工作人员年度考核个人总结
2015/02/12 职场文书
2015年教师见习期工作总结
2015/05/20 职场文书
python模拟浏览器 使用selenium进入好友QQ空间并留言
2022/04/12 Python