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用fork来创建子进程注意事项
Jul 03 Python
利用python批量修改word文件名的方法示例
Oct 17 Python
破解安装Pycharm的方法
Oct 19 Python
Python中最大递归深度值的探讨
Mar 05 Python
Python 二叉树的层序建立与三种遍历实现详解
Jul 29 Python
python调用Matplotlib绘制分布点图
Oct 18 Python
python pandas移动窗口函数rolling的用法
Feb 29 Python
浅谈Python线程的同步互斥与死锁
Mar 22 Python
Django 解决阿里云部署同步数据库报错的问题
May 14 Python
使用Python FastAPI构建Web服务的实现
Jun 08 Python
Python基于network模块制作电影人物关系图
Jun 19 Python
Python txt文件常用读写操作代码实例
Aug 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
使用zend studio for eclipse不能激活代码提示功能的解决办法
2009/10/11 PHP
php自定义函数call_user_func和call_user_func_array详解
2011/07/14 PHP
基于magic_quotes_gpc与magic_quotes_runtime的区别与使用介绍
2013/04/22 PHP
关于PHPDocument 代码注释规范的总结
2013/06/25 PHP
php中使用getimagesize获取图片、flash等文件的尺寸信息实例
2014/04/29 PHP
php判断数组中是否存在指定键(key)的方法
2015/03/17 PHP
php实现将wav文件转换成图像文件并在页面中显示的方法
2015/04/21 PHP
PHP实现数据分页显示的简单实例
2016/05/26 PHP
JS的IE和Firefox兼容性集锦
2006/12/11 Javascript
利用webqq协议使用python登录qq发消息源码参考
2013/04/08 Javascript
jQuery获得内容和属性示例代码
2014/01/16 Javascript
JavaScript控制各种浏览器全屏模式的方法、属性和事件介绍
2014/04/03 Javascript
使用script的src实现跨域和类似ajax效果
2014/11/10 Javascript
jQuery中noconflict函数的实现原理分解
2015/02/03 Javascript
jQuery+PHP星级评分实现方法
2015/10/02 Javascript
JavaScript对象参数的引用传递
2016/01/14 Javascript
学习JavaScript设计模式之享元模式
2016/01/18 Javascript
一览画面点击复选框后获取多个id值的方法
2016/05/30 Javascript
Jquery Easyui验证组件ValidateBox使用详解(20)
2016/12/18 Javascript
[js高手之路]从原型链开始图解继承到组合继承的产生详解
2017/08/28 Javascript
原生JS+HTML5实现跟随鼠标一起流动的粒子动画效果
2018/05/03 Javascript
JS内置对象和Math对象知识点详解
2020/04/03 Javascript
prettier自动格式化去换行的实现代码
2020/08/25 Javascript
深入理解javascript中的this
2021/02/08 Javascript
[52:32]完美世界DOTA2联赛PWL S2 Magma vs LBZS 第三场 11.18
2020/11/18 DOTA
python制作企业邮箱的爆破脚本
2016/10/05 Python
django 实现编写控制登录和访问权限控制的中间件方法
2019/01/15 Python
react+django清除浏览器缓存的几种方法小结
2019/07/17 Python
怀旧收藏品和经典纪念品:Betty’s Attic
2018/08/29 全球购物
为女性购买传统的印度服装和婚纱:Kalkifashion
2019/07/22 全球购物
出生医学证明样本
2014/01/17 职场文书
大学学风建设方案
2014/05/04 职场文书
电子专业毕业生自荐信
2014/05/25 职场文书
同步小康驻村工作简报
2015/07/20 职场文书
基于PyQT5制作一个桌面摸鱼工具
2022/02/15 Python