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 27 Python
Python实现保证只能运行一个脚本实例
Jun 24 Python
分享一下Python 开发者节省时间的10个方法
Oct 02 Python
Python实现屏幕截图的代码及函数详解
Oct 01 Python
python 打印直角三角形,等边三角形,菱形,正方形的代码
Nov 21 Python
Python 查看文件的编码格式方法
Dec 21 Python
python scipy求解非线性方程的方法(fsolve/root)
Nov 12 Python
python的concat等多种用法详解
Nov 28 Python
golang/python实现归并排序实例代码
Aug 30 Python
Jupyter Notebook安装及使用方法解析
Nov 12 Python
利用Python将多张图片合成视频的实现
Nov 23 Python
python邮件中附加文字、html、图片、附件实现方法
Jan 04 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 批量替换程序的具体实现代码
2013/10/04 PHP
php 表单提交大量数据发生丢失的解决方法
2014/03/03 PHP
PHP基于文件存储实现缓存的方法
2015/07/20 PHP
Javascript Object.extend
2010/05/18 Javascript
8款非常棒的响应式jQuery 幻灯片插件推荐
2012/02/02 Javascript
caller和callee的区别介绍及演示结果
2013/03/10 Javascript
jquery动态增加删减表格行特效
2015/11/20 Javascript
快速学习jQuery插件 Cookie插件使用方法
2015/12/01 Javascript
js倒计时简单实现方法
2015/12/17 Javascript
详解javascript跨浏览器事件处理程序
2016/03/27 Javascript
JavaScript实现翻页功能(附效果图)
2017/02/16 Javascript
JS分页的实现(同步与异步)
2017/09/16 Javascript
vue+vuecli+webpack中使用mockjs模拟后端数据的示例
2017/10/24 Javascript
原生js实现移动端触摸轮播的示例代码
2017/12/22 Javascript
在vue中通过axios异步使用echarts的方法
2018/01/13 Javascript
node.js博客项目开发手记
2018/03/16 Javascript
AngularJS下$http服务Post方法传递json参数的实例
2018/03/29 Javascript
layui实现下拉框三级联动
2019/07/26 Javascript
element日历calendar组件上月、今天、下月、日历块点击事件及模板源码
2020/07/27 Javascript
解决PyCharm中光标变粗的问题
2017/08/05 Python
详解Pytorch 使用Pytorch拟合多项式(多项式回归)
2018/05/24 Python
Django跨域请求CSRF的方法示例
2018/11/11 Python
树莓派用python中的OpenCV输出USB摄像头画面
2019/06/22 Python
Python中正反斜杠(‘/’和‘\’)的意义与用法
2019/08/12 Python
python读取word 中指定位置的表格及表格数据
2019/10/23 Python
使用遗传算法求二元函数的最小值
2020/02/11 Python
python Plotly绘图工具的简单使用
2020/03/03 Python
Python matplotlib 绘制双Y轴曲线图的示例代码
2020/06/12 Python
利用CSS3实现的文字定时向上滚动
2016/08/29 HTML / CSS
FLOS美国官网:意大利高级照明工艺的传奇
2018/08/07 全球购物
如何安装ruby on rails
2014/02/09 面试题
甜美蛋糕店创业计划书
2014/01/30 职场文书
golang 在windows中设置环境变量的操作
2021/04/29 Golang
MySQL索引知识的一些小妙招总结
2021/05/10 MySQL
Python实现8种常用抽样方法
2021/06/27 Python
Redis性能监控的实现
2021/07/09 Redis