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正则表达式介绍
Aug 06 Python
python多线程抓取天涯帖子内容示例
Apr 03 Python
基于Python实现的扫雷游戏实例代码
Aug 01 Python
Python运算符重载用法实例分析
Jun 01 Python
Jupyter中直接显示Matplotlib的图形方法
May 24 Python
在NumPy中创建空数组/矩阵的方法
Jun 15 Python
解决Pycharm出现的部分快捷键无效问题
Oct 22 Python
局域网内python socket实现windows与linux间的消息传送
Apr 19 Python
numpy和pandas中数组的合并、拉直和重塑实例
Jun 28 Python
python实现网站用户名密码自动登录功能
Aug 09 Python
Python Gitlab Api 使用方法
Aug 28 Python
python将音频进行变速的操作方法
Apr 08 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+Ajax检测用户名或邮件注册时是否已经存在实例教程
2014/08/23 PHP
php中html_entity_decode实现HTML实体转义
2018/06/13 PHP
javascript 动态生成私有变量访问器
2009/12/06 Javascript
javascript如何创建表格(javascript绘制表格的二种方法)
2013/12/10 Javascript
类似天猫商品详情随浏览器移动的示例代码
2014/02/27 Javascript
JavaScript AJAX之惰性载入函数
2014/08/27 Javascript
JavaScript检测字符串中是否含有html标签实现方法
2015/07/01 Javascript
JavaScript中利用Array和Object实现Map的方法
2015/07/27 Javascript
JS的框架Polymer中的dom-if和is属性使用说明
2015/07/29 Javascript
prototype.js常用函数详解
2016/06/18 Javascript
总结Node.js中的一些错误类型
2016/08/15 Javascript
AngularJS通过$location获取及改变当前页面的URL
2016/09/23 Javascript
JavaScript利用闭包实现模块化
2017/01/13 Javascript
JavaScript实现选中文字提示新浪微博分享效果
2017/06/15 Javascript
微信小程序通过保存图片分享到朋友圈功能
2018/05/24 Javascript
vue+axios 前端实现登录拦截的两种方式(路由拦截、http拦截)
2018/10/24 Javascript
如何为你的JavaScript代码日志着色详解
2019/04/08 Javascript
node省市区三级数据性能测评实例分析
2019/11/06 Javascript
vue使用require.context实现动态注册路由
2020/12/25 Vue.js
在Django的视图中使用数据库查询的方法
2015/07/16 Python
Pycharm设置界面全黑的方法
2018/05/23 Python
Python第三方Window模块文件的几种安装方法
2018/11/22 Python
python 接收处理外带的参数方法
2018/12/03 Python
python中dir()与__dict__属性的区别浅析
2018/12/10 Python
PyQt5 实现给窗口设置背景图片的方法
2019/06/13 Python
将matplotlib绘图嵌入pyqt的方法示例
2020/01/08 Python
PyQT5速成教程之Qt Designer介绍与入门
2020/11/02 Python
美丽的现代设计家具:2Modern
2018/07/26 全球购物
Linux文件系统类型
2012/09/16 面试题
入党申请人的自我鉴定
2013/12/01 职场文书
花坛标语大全
2014/06/30 职场文书
乡镇八一建军节活动方案
2014/08/24 职场文书
2015大学生实训报告
2014/11/05 职场文书
作文评语怎么写
2014/12/25 职场文书
2015医德医风个人工作总结
2015/04/02 职场文书
阿里云国际版 使用Nginx作为HTTPS转发代理服务器
2022/05/11 Servers