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 布尔操作实现代码
Mar 23 Python
python生成日历实例解析
Aug 21 Python
简单介绍Python的轻便web框架Bottle
Apr 08 Python
Python+matplotlib实现华丽的文本框演示代码
Jan 22 Python
python检测主机的连通性并记录到文件的实例
Jun 21 Python
Python使用combinations实现排列组合的方法
Nov 13 Python
将pandas.dataframe的数据写入到文件中的方法
Dec 07 Python
Python中常用的8种字符串操作方法
May 06 Python
Python协程 yield与协程greenlet简单用法示例
Nov 22 Python
新建文件时Pycharm中自动设置头部模板信息的方法
Apr 17 Python
Pandas中两个dataframe的交集和差集的示例代码
Dec 13 Python
关于python pygame游戏进行声音添加的技巧
Oct 24 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利用单例模式实现日志处理类库
2014/02/10 PHP
PHP页面实现定时跳转的方法
2014/10/31 PHP
PHP对文件夹递归执行chmod命令的方法
2015/06/19 PHP
PHP+sqlite数据库操作示例(创建/打开/插入/检索)
2016/05/26 PHP
PHP进阶学习之依赖注入与Ioc容器详解
2019/06/19 PHP
thinkPHP事务操作简单案例分析
2019/10/17 PHP
javascript中万恶的function实例分析
2011/05/25 Javascript
EasyUI的treegrid组件动态加载数据问题的解决办法
2011/12/11 Javascript
node.js chat程序如何实现Ajax long-polling长链接刷新模式
2012/03/13 Javascript
jquery的$getjson调用并获取远程的JSON字符串问题
2012/12/10 Javascript
js动态修改整个页面样式达到换肤效果
2014/05/23 Javascript
PHP结合jQuery实现的评论顶、踩功能
2015/07/22 Javascript
简单理解vue中Props属性
2016/10/27 Javascript
JavaScript实现向select下拉框中添加和删除元素的方法
2017/03/07 Javascript
微信小程序录音与播放录音功能
2017/12/25 Javascript
使用 vue-i18n 切换中英文效果
2018/05/23 Javascript
解决微信小程序scroll-view组件无横向滚动的问题
2020/02/04 Javascript
VUE 单页面使用 echart 窗口变化时的用法
2020/07/30 Javascript
pytz格式化北京时间多出6分钟问题的解决方法
2019/06/21 Python
浅谈keras的深度模型训练过程及结果记录方式
2020/01/24 Python
深入了解python列表(LIST)
2020/06/08 Python
编写python代码实现简单抽奖器
2020/10/20 Python
Python使用grequests并发发送请求的示例
2020/11/05 Python
CSS Grid布局教程之浏览器开启CSS Grid Layout汇总
2014/12/30 HTML / CSS
Molton Brown美国官网:奢华美容、香水、沐浴和身体护理
2020/09/02 全球购物
万代美国官网:PREMIUM BANDAI USA
2020/09/11 全球购物
文职个人求职信范文
2013/09/23 职场文书
2014年自我评价
2014/01/04 职场文书
《我爱祖国》演讲稿1000字
2014/09/26 职场文书
预备党员2014年第四季度思想汇报范文
2014/10/25 职场文书
2014年教育工作总结
2014/11/26 职场文书
小学三八妇女节活动总结
2015/02/06 职场文书
2015年街道除四害工作总结
2015/05/15 职场文书
导游词之阳朔遇龙河
2019/12/16 职场文书
Nginx服务器添加Systemd自定义服务过程解析
2021/03/31 Servers
Python办公自动化之教你如何用Python将任意文件转为PDF格式
2021/06/28 Python