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实现自动登录人人网并访问最近来访者实例
Sep 26 Python
python中的__slots__使用示例
Feb 26 Python
使用httplib模块来制作Python下HTTP客户端的方法
Jun 19 Python
python 禁止函数修改列表的实现方法
Aug 03 Python
python版微信跳一跳游戏辅助
Jan 11 Python
python集合是否可变总结
Jun 20 Python
Django接收post前端返回的json格式数据代码实现
Jul 31 Python
pandas DataFrame的修改方法(值、列、索引)
Aug 02 Python
Python hashlib加密模块常用方法解析
Dec 18 Python
使用Python串口实时显示数据并绘图的例子
Dec 26 Python
利用Python多线程实现图片下载器
Mar 25 Python
Django数据库(SQlite)基本入门使用教程
Jul 07 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下对数组进行排序的函数
2010/08/08 PHP
用PHP实现Ftp用户的在线管理
2012/02/16 PHP
php中计算未知长度的字符串哪个字符出现的次数最多的代码
2012/08/14 PHP
php实现的mongodb操作类实例
2015/04/03 PHP
php微信公众平台开发之获取用户基本信息
2015/08/17 PHP
php图片添加文字水印实现代码
2016/03/15 PHP
PHP排序算法之冒泡排序(Bubble Sort)实现方法详解
2018/04/20 PHP
JavaScript入门教程(10) 认识其他对象
2009/01/31 Javascript
使用jQuery操作Cookies的实现代码
2011/10/09 Javascript
js实现动态改变字体大小代码
2014/01/02 Javascript
JS实现清除指定cookies的方法
2014/09/20 Javascript
jQuery实现的导航条切换可显示隐藏
2014/10/22 Javascript
JS+DIV+CSS排版布局实现美观的选项卡效果
2015/10/10 Javascript
如何正确理解javascript的模块化
2017/03/02 Javascript
python实现zencart产品数据导入到magento(python导入数据)
2014/04/03 Python
在Python中实现贪婪排名算法的教程
2015/04/17 Python
Python中encode()方法的使用简介
2015/05/18 Python
Python中super关键字用法实例分析
2015/05/28 Python
Python标准库06之子进程 (subprocess包) 详解
2016/12/07 Python
Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例
2018/04/26 Python
Python装饰器模式定义与用法分析
2018/08/06 Python
使用Python制作简单的小程序IP查看器功能
2019/04/16 Python
使用python画社交网络图实例代码
2019/07/10 Python
python实现登录密码重置简易操作代码
2019/08/14 Python
城市轨道专业个人求职信范文
2013/09/23 职场文书
房地产员工找工作的自我评价
2013/11/15 职场文书
小学教师管理制度
2014/01/18 职场文书
清正廉洁演讲稿
2014/05/22 职场文书
会计岗位说明书
2014/07/29 职场文书
个人四风问题原因分析及整改措施
2014/09/28 职场文书
学校施工安全责任书
2015/01/29 职场文书
中班下学期个人总结
2015/02/12 职场文书
2015年五一劳动节演讲稿
2015/03/18 职场文书
2015年项目经理工作总结
2015/04/30 职场文书
社区党建工作总结2015
2015/05/13 职场文书
pycharm无法安装cv2模块问题
2022/05/20 Python