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 相关文章推荐
Python利用pyHook实现监听用户鼠标与键盘事件
Aug 21 Python
Python的Flask框架应用调用Redis队列数据的方法
Jun 06 Python
Python编程使用NLTK进行自然语言处理详解
Nov 16 Python
python 动态加载的实现方法
Dec 22 Python
Python实现PS滤镜的万花筒效果示例
Jan 23 Python
完美解决Pycharm无法导入包的问题 Unresolved reference
May 18 Python
Python实现基于C/S架构的聊天室功能详解
Jul 07 Python
使用python实现http及ftp服务进行数据传输的方法
Oct 26 Python
通过PHP与Python代码对比的语法差异详解
Jul 10 Python
pytorch实现线性拟合方式
Jan 15 Python
python db类用法说明
Jul 07 Python
小结Python的反射机制
Sep 28 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
咖啡豆要不要放冰箱的原因
2021/03/04 冲泡冲煮
一个显示天气预报的程序
2006/10/09 PHP
基于php实现长连接的方法与注意事项的问题
2013/05/10 PHP
PHP使用静态方法的几个注意事项
2014/09/16 PHP
PHP CodeIgniter分页实例及多条件查询解决方案(推荐)
2017/05/20 PHP
JavaScript中document对象使用详解
2015/01/06 Javascript
JavaScript学习笔记之Cookie对象
2015/01/22 Javascript
原生js结合html5制作小飞龙的简易跳球
2015/03/30 Javascript
JavaScript中模拟实现jsonp
2015/06/19 Javascript
jQuery EasyUI Pagination实现分页的常用方法
2016/05/21 Javascript
canvas绘制表盘时钟
2017/01/23 Javascript
简单明了区分escape、encodeURI和encodeURIComponent
2018/05/26 Javascript
详解用Webpack与Babel配置ES6开发环境
2019/03/12 Javascript
vue路由跳转传参数的方法
2019/05/06 Javascript
VUE前后端学习tab写法实例
2019/08/06 Javascript
JS实现简单省市二级联动
2019/11/27 Javascript
手把手带你入门微信小程序新框架Kbone的使用
2020/02/25 Javascript
ES6 async、await的基本使用方法示例
2020/06/06 Javascript
解决vue一个页面中复用同一个echarts组件的问题
2020/07/19 Javascript
Python中for循环和while循环的基本使用方法
2015/08/21 Python
Python 自动化表单提交实例代码
2017/06/08 Python
python 实现Flask中返回图片流给前端展示
2020/01/09 Python
python中编写函数并调用的知识点总结
2021/01/13 Python
英国袜子店:Sock Shop
2017/01/11 全球购物
Big Green Smile德国网上商店:提供各种天然产品
2018/05/23 全球购物
为数据库创建索引都需要注意些什么
2012/07/17 面试题
顺丰快递Java软件工程师面试题
2015/07/31 面试题
中学生自我鉴定
2014/02/04 职场文书
啦啦队口号大全
2014/06/16 职场文书
幼儿园校车安全责任书
2015/05/08 职场文书
毕业生登记表班级意见
2015/06/05 职场文书
2015暑假社会调查报告
2015/07/13 职场文书
2016年党支部公开承诺书
2016/03/25 职场文书
go:垃圾回收GC触发条件详解
2021/04/24 Golang
JUnit5常用注解的使用
2021/07/02 Java/Android
webpack的移动端适配方案小结
2021/07/25 Javascript