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之PyUnit单元测试实例
Oct 11 Python
python实现从一组颜色中找出与给定颜色最接近颜色的方法
Mar 19 Python
Python实现Linux中的du命令
Jun 12 Python
Python Nose框架编写测试用例方法
Oct 26 Python
对Python3之进程池与回调函数的实例详解
Jan 22 Python
Python使用sqlalchemy模块连接数据库操作示例
Mar 13 Python
Python获取数据库数据并保存在excel表格中的方法
Jun 12 Python
Python虚拟环境的原理及使用详解
Jul 02 Python
python爬虫 正则表达式解析
Sep 28 Python
Python tkinter实现简单加法计算器代码实例
May 13 Python
class类在python中获取金融数据的实例方法
Dec 10 Python
CocosCreator ScrollView优化系列之分帧加载
Apr 14 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 多维数组排序实现代码
2009/08/05 PHP
PHP实现清除wordpress里恶意代码
2015/10/21 PHP
PHP简单创建压缩图的方法
2016/08/24 PHP
php实现的简单中文验证码功能示例
2017/01/03 PHP
laravel 5.5 关闭token的3种实现方式
2019/10/24 PHP
php redis setnx分布式锁简单原理解析
2020/10/23 PHP
JavaScript 继承的实现
2009/07/09 Javascript
javascript实现百度地图鼠标滑动事件显示、隐藏
2015/04/02 Javascript
jquery实现仿Flash的横向滑动菜单效果代码
2015/09/17 Javascript
jQuery bt气泡实现悬停显示及移开隐藏功能的方法
2016/07/12 Javascript
基于MVC方式实现三级联动(JavaScript)
2017/01/23 Javascript
ES6新特性八:async函数用法实例详解
2017/04/21 Javascript
js实现移动端轮播图效果
2020/12/09 Javascript
简单实现vue验证码60秒倒计时功能
2017/10/11 Javascript
完美解决axios跨域请求出错的问题
2018/02/05 Javascript
electron demo项目npm install安装失败的解决方法
2018/02/06 Javascript
详解nodejs 配置文件处理方案
2019/01/02 NodeJs
vue-router为激活的路由设置样式操作
2020/07/18 Javascript
一篇文章带你搞懂Vue虚拟Dom与diff算法
2020/08/25 Javascript
[02:46]解说DC:感谢430陪伴我们的DOTA2国际邀请赛岁月
2016/06/29 DOTA
[57:29]Alliance vs KG 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/17 DOTA
Python中的True,False条件判断实例分析
2015/01/12 Python
使用优化器来提升Python程序的执行效率的教程
2015/04/02 Python
python 删除指定时间间隔之前的文件实例
2018/04/24 Python
python 实现生成均匀分布的点
2019/12/05 Python
PyTorch和Keras计算模型参数的例子
2020/01/02 Python
Python爬虫爬取微信朋友圈
2020/08/06 Python
Ubuntu配置Pytorch on Graph (PoG)环境过程图解
2020/11/19 Python
python 如何停止一个死循环的线程
2020/11/24 Python
Python利用imshow制作自定义渐变填充柱状图(colorbar)
2020/12/10 Python
缅甸网上购物:Shop.com.mm
2017/12/05 全球购物
软件测试面试题
2015/10/21 面试题
师范教师毕业鉴定
2014/01/13 职场文书
品质标语大全
2014/06/21 职场文书
模具设计与制造专业自荐书
2014/07/01 职场文书
总结Python变量的相关知识
2021/06/28 Python