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复制文件代码实现
Dec 23 Python
Python的shutil模块中文件的复制操作函数详解
Jul 05 Python
python字典操作实例详解
Nov 16 Python
Python爬虫信息输入及页面的切换方法
May 11 Python
Python解决两个整数相除只得到整数部分的实例
Nov 10 Python
Python对象转换为json的方法步骤
Apr 25 Python
python调用摄像头拍摄数据集
Jun 01 Python
Python 70行代码实现简单算式计算器解析
Aug 30 Python
python matplotlib饼状图参数及用法解析
Nov 04 Python
python flask搭建web应用教程
Nov 19 Python
pytorch实现线性拟合方式
Jan 15 Python
python字符串拼接.join()和拆分.split()详解
Nov 23 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
简单的过滤字符串中的HTML标记
2006/12/25 PHP
php实例分享之通过递归实现删除目录下的所有文件详解
2014/05/15 PHP
php中的curl_multi系列函数使用例子
2014/07/29 PHP
PHP判断JSON对象是否存在的方法(推荐)
2016/07/06 PHP
PHP递归实现文件夹的复制、删除、查看大小操作示例
2017/08/11 PHP
JS获取文件大小方法小结
2015/12/08 Javascript
JavaScript笔记之数据属性和存储器属性
2016/03/31 Javascript
JS基于正则截取替换特定字符之间字符串操作示例
2017/02/03 Javascript
bootstrap如何让dropdown menu按钮式下拉框长度一致
2017/04/10 Javascript
JavaScript 获取元素在父节点中的下标(推荐)
2017/06/28 Javascript
js防刷新的倒计时代码 js倒计时代码
2017/09/06 Javascript
layer弹出层扩展主题的方法
2019/09/11 Javascript
vue输入框使用模糊搜索功能的实现代码
2020/05/26 Javascript
小程序实现多个选项卡切换
2020/06/19 Javascript
Python发送form-data请求及拼接form-data内容的方法
2016/03/05 Python
浅谈Python由__dict__和dir()引发的一些思考
2017/10/30 Python
利用python库在局域网内传输文件的方法
2018/06/04 Python
Python实现程序判断季节的代码示例
2019/01/28 Python
基于Python实现扑克牌面试题
2019/12/11 Python
python将图片转base64,实现前端显示
2020/01/09 Python
利用django model save方法对未更改的字段依然进行了保存
2020/03/28 Python
keras用auc做metrics以及早停实例
2020/07/02 Python
Python3.7安装pyaudio教程解析
2020/07/24 Python
CSS3+JavaScript实现炫酷呼吸效果的示例代码
2020/06/15 HTML / CSS
html5 web本地存储将取代我们的cookie
2012/12/26 HTML / CSS
阿根廷旅游网站:almundo阿根廷
2018/02/12 全球购物
非常详细的C#面试题集
2016/07/13 面试题
艺术专业大学生自我评价
2013/09/22 职场文书
公司薪酬管理制度
2014/01/31 职场文书
优良学风班总结材料
2014/02/08 职场文书
小学生国旗下演讲稿
2014/04/25 职场文书
小学课外活动总结
2014/07/09 职场文书
学习群众路线的心得体会
2014/11/05 职场文书
贷款收入证明范本
2015/06/12 职场文书
2016优秀毕业生个人事迹材料
2016/02/29 职场文书
ThinkPHP5和ThinkPHP6的区别
2021/03/31 PHP