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 11 Python
python通过urllib2爬网页上种子下载示例
Feb 24 Python
Python和Ruby中each循环引用变量问题(一个隐秘BUG?)
Jun 04 Python
Python对两个有序列表进行合并和排序的例子
Jun 13 Python
python正则表达式之作业计算器
Mar 18 Python
Python中list初始化方法示例
Sep 18 Python
python中的随机函数小结
Jan 27 Python
Python 删除整个文本中的空格,并实现按行显示
Jul 24 Python
在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例
Jan 29 Python
对python 自定义协议的方法详解
Feb 13 Python
在cmd中查看python的安装路径方法
Jul 03 Python
Numpy之将矩阵拉成向量的实例
Nov 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中的时间显示
2007/01/18 PHP
php采集自中央气象台范围覆盖全国的天气预报代码实例
2015/01/04 PHP
php实现的表单验证类完整示例
2019/08/13 PHP
轻轻松松学JS调试(不下载任何工具)
2010/04/14 Javascript
深入理解JavaScript系列(7) S.O.L.I.D五大原则之开闭原则OCP
2012/01/15 Javascript
JavaScript实现的一个日期格式化函数分享
2014/12/06 Javascript
常用的js验证和数据处理总结
2016/08/02 Javascript
怎样判断jQuery当前元素是隐藏还是显示
2016/11/23 Javascript
javascript实现的图片预览功能
2017/03/25 Javascript
Vue实现virtual-dom的原理简析
2017/07/10 Javascript
在Vue项目中使用snapshot测试的具体使用
2019/04/16 Javascript
vue 实现移动端键盘搜索事件监听
2019/11/06 Javascript
微信小程序实现多选框全选与反全选及购物车中删除选中的商品功能
2019/12/17 Javascript
[02:50]2014DOTA2 TI预选赛预选赛 大神专访第一弹!
2014/05/21 DOTA
[43:24]VG vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
Python采用Django制作简易的知乎日报API
2016/08/03 Python
python通过pip更新所有已安装的包实现方法
2017/05/19 Python
Python内置函数reversed()用法分析
2018/03/20 Python
python版本的仿windows计划任务工具
2018/04/30 Python
python图形开发GUI库wxpython使用方法详解
2020/02/14 Python
100%有机精油,美容油:House of Pure Essence
2018/10/30 全球购物
Clarks鞋澳大利亚官方网站:Clarks Australia
2019/12/25 全球购物
System.Array.CopyTo()和System.Array.Clone()有什么区别
2016/06/20 面试题
口腔工艺技术专业毕业生自荐信
2013/09/27 职场文书
船舶专业个人求职信范文
2014/01/02 职场文书
出国签证在职证明
2014/01/16 职场文书
新员工入职感言
2014/02/01 职场文书
企业节能减排实施方案
2014/03/19 职场文书
好书伴我成长演讲稿
2014/05/14 职场文书
企业承诺书怎么写
2014/05/24 职场文书
个性车贴标语
2014/06/24 职场文书
土建施工员岗位职责
2014/07/16 职场文书
说好普通话圆梦你我他演讲稿
2014/09/21 职场文书
婚宴领导致辞
2015/07/28 职场文书
电台广播稿范文
2015/08/19 职场文书
Mysql Show Profile
2021/04/05 MySQL