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实现带百分比的进度条
Jun 28 Python
Python实现小数转化为百分数的格式化输出方法示例
Sep 20 Python
机器学习的框架偏向于Python的13个原因
Dec 07 Python
Django中的文件的上传的几种方式
Jul 23 Python
python 3.7.0 下pillow安装方法
Aug 27 Python
Python使用try except处理程序异常的三种常用方法分析
Sep 05 Python
Python3实现获取图片文字里中文的方法分析
Dec 13 Python
在Python中append以及extend返回None的例子
Jul 20 Python
python实现while循环打印星星的四种形状
Nov 23 Python
Python列表倒序输出及其效率详解
Mar 04 Python
DataFrame 数据合并实现(merge,join,concat)
Jun 14 Python
一文搞懂如何实现Go 超时控制
Mar 30 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使用wordwrap格式化文本段落的方法
2015/03/17 PHP
详解php语言最牛掰的Laravel框架
2017/11/20 PHP
Yii2框架实现利用mpdf创建pdf文件功能示例
2019/02/08 PHP
PHP切割整数工具类似微信红包金额分配的思路详解
2019/09/18 PHP
Laravel 已登陆用户再次查看登陆页面的自动跳转设置方法
2019/09/30 PHP
JavaScript 页面坐标相关知识整理
2010/01/09 Javascript
Extjs gridpanel 出现横向滚动条问题的解决方法
2011/07/04 Javascript
jquery中ajax学习笔记一
2011/10/16 Javascript
node.js中的http.response.removeHeader方法使用说明
2014/12/14 Javascript
jQuery滚动条插件nanoscroller使用指南
2015/04/21 Javascript
ECMAScript6块级作用域及新变量声明(let)
2015/06/12 Javascript
jQuery实现仿QQ头像闪烁效果的文字闪动提示代码
2015/11/03 Javascript
js给table赋值的实例代码
2016/10/13 Javascript
javaScript动态添加Li元素的实例
2018/02/24 Javascript
JavaScript变量声明var,let.const及区别浅析
2018/04/23 Javascript
小程序图片剪裁加旋转的示例代码
2018/07/10 Javascript
Vue.js 通过jQuery ajax获取数据实现更新后重新渲染页面的方法
2018/08/09 jQuery
Angular 实现输入框中显示文章标签的实例代码
2018/11/07 Javascript
为react组件库添加typescript类型提示的方法
2020/06/15 Javascript
vue keep-alive实现多组件嵌套中个别组件存活不销毁的操作
2020/10/30 Javascript
Python 创建子进程模块subprocess详解
2015/04/08 Python
基于wxpython开发的简单gui计算器实例
2015/05/30 Python
Python中matplotlib中文乱码解决办法
2017/05/12 Python
TensorFlow实现MLP多层感知机模型
2018/03/09 Python
python使用magic模块进行文件类型识别方法
2018/12/08 Python
Django项目uwsgi+Nginx保姆级部署教程实现
2020/04/19 Python
css3之UI元素状态伪类选择器实例演示
2017/08/11 HTML / CSS
英国的一家创新礼品和小工具零售商:Menkind
2019/08/24 全球购物
外贸业务员的岗位职责
2013/11/23 职场文书
高中英语教学反思
2014/02/04 职场文书
大学班级干部的自我评价分享
2014/02/10 职场文书
大学新生入学教育方案
2014/05/16 职场文书
2015年安全月活动总结
2015/03/26 职场文书
党员转正意见怎么写
2015/06/03 职场文书
MySQL 亿级数据导入导出及迁移笔记
2021/06/18 MySQL
详解Oracle块修改跟踪功能
2021/11/07 Oracle