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编写一个简单的俄罗斯方块游戏的教程
Apr 03 Python
python避免死锁方法实例分析
Jun 04 Python
轻松掌握python设计模式之策略模式
Nov 18 Python
pandas groupby 分组取每组的前几行记录方法
Apr 20 Python
python将处理好的图像保存到指定目录下的方法
Jan 10 Python
在Python中,不用while和for循环遍历列表的实例
Feb 20 Python
如何通过50行Python代码获取公众号全部文章
Jul 12 Python
基于python 微信小程序之获取已存在模板消息列表
Aug 05 Python
python requests证书问题解决
Sep 05 Python
Python turtle库绘制菱形的3种方式小结
Nov 23 Python
pymysql模块的操作实例
Dec 17 Python
Python爬虫获取op.gg英雄联盟英雄对位胜率的源码
Jan 29 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的FTP学习(三)
2006/10/09 PHP
php制作动态随机验证码
2015/02/12 PHP
php curl请求信息和返回信息设置代码实例
2015/04/27 PHP
基于jsTree的无限级树JSON数据的转换代码
2010/07/27 Javascript
jQuery链式操作如何实现以及为什么要用链式操作
2013/01/17 Javascript
jQuery产品间断向下滚动效果核心代码
2014/05/08 Javascript
Jquery图片延迟加载插件jquery.lazyload.js的使用方法
2014/05/21 Javascript
js获取当前页面的url网址信息
2014/06/12 Javascript
select多选 multiple的使用示例
2014/06/16 Javascript
HTML5游戏引擎LTweenLite实现的超帅动画效果(附demo源码下载)
2016/01/26 Javascript
javascript特殊文本输入框网页特效
2016/09/13 Javascript
JavaScript实现鼠标点击导航栏变色特效
2017/02/08 Javascript
ES6学习之变量的解构赋值
2017/02/12 Javascript
JS+html5 canvas实现的简单绘制折线图效果示例
2017/03/13 Javascript
详解nodejs操作mongodb数据库封装DB类
2017/04/10 NodeJs
javascript数据结构中栈的应用之符号平衡问题
2017/04/11 Javascript
jQuery修改DOM结构_动力节点Java学院整理
2017/07/05 jQuery
微信小程序时间选择插件使用详解
2018/12/28 Javascript
vue路由插件之vue-route
2019/06/13 Javascript
Vue 中可以定义组件模版的几种方式
2019/08/06 Javascript
JS手写一个自定义Promise操作示例
2020/03/16 Javascript
通过实例浅析Python对比C语言的编程思想差异
2015/08/30 Python
用Python下载一个网页保存为本地的HTML文件实例
2018/05/21 Python
PyCharm在新窗口打开项目的方法
2019/01/17 Python
Django组件content-type使用方法详解
2019/07/19 Python
pytorch实现onehot编码转为普通label标签
2020/01/02 Python
python自动提取文本中的时间(包含中文日期)
2020/08/31 Python
pycharm最新激活码有效期至2100年(亲测可用)
2021/02/05 Python
在校生钳工实习自我鉴定
2013/09/19 职场文书
行政前台岗位职责
2013/12/04 职场文书
建筑工程管理专业自荐信范文
2013/12/28 职场文书
低碳环保口号
2014/06/12 职场文书
高中运动会广播稿
2014/09/16 职场文书
学校食堂食品安全承诺书
2015/04/29 职场文书
小平您好观后感
2015/06/09 职场文书
利用python Pandas实现批量拆分Excel与合并Excel
2021/05/23 Python