Python实现批量将word转html并将html内容发布至网站的方法
作者:爱兔一生 发布时间:2021-08-27 04:17:45
标签:Python,word,html
本文实例讲述了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程序设计有所帮助。


猜你喜欢
- 1.apache配置文件中打开vhost的配置LoadModule vhost_alias_module modules/mod_vhost
- 写在前面的话:Part 1记得刚毕业那时,常幻想着自己是个大艺术家,满怀憧憬的想找一份理想的工作。后来入了行,慢慢的发现自己好像不是这块料;
- 大家觉得在接手遗留代码时,见到什么东东是最让人感到不耐烦的?复杂无比的 UML ?我觉得不是。我的答案是,超过两个 else 的 if ,或
- 本文实例讲述了mysql自定义函数原理与用法。分享给大家供大家参考,具体如下:本文内容:什么是函数函数的创建函数的调用函数的查看函数的修改函
- 答案先有 “类属性”,再有 “运行 metaclass”#
- 如下所示:url = u'http://tieba.baidu.com/f?kw=权利的游戏&ie=utf-8&pn
- 启动targetcli时遭遇ImportError: cannot import name ALUATargetPortGrou
- 在Linux、Windows、Mac OS的命令行窗口或Shell窗口,执行python命令,启动Python交互式解释器。交互式解释器会等
- 用for循环和海龟绘图实现漂亮的螺旋线A.课程内容本节课通过绘制复杂的螺旋线来深入学习for循环和range()函数的用法。深入了解循环的程
- shutil --High-level file operations 高级的文件操作模块os模块提供了对目录或者文件的新建/删除/查看文件
- 前言 FTP(File Transfer Protocol)是文件传输协议的简称。用于Internet上的控制文件的双向传输。同时,它也是一
- 本文实例讲述了python实现对象列表根据某个属性排序的方法。分享给大家供大家参考,具体如下:对于一个已有的python list, 里面的
- 01、文件操作文件是操作系统提供给用户/应用程序操作硬盘的一个虚拟的概念/接口用户/应用程序可以通过文件将数据永久保存在硬盘中用户/应用程序
- 下载:pip install apschedulerpip install django-apscheduler将 django-apsch
- 目录前言什么是 websocketwebsocket 通信原理和机制websocket 的特点构建实时日志跟踪的小例子前言websocket
- 写在前面从本节开始,计算机视觉教程进入第三章节——图像特征提取。在本章,你会见到一张简简单单的图片中
- Sql server聚合函数在实际工作中应对各种需求使用的还是很广泛的,对于聚合函数的优化自然也就成为了一个重点,一个程序优化的好不好直接决
- 假设你需要允许在Hero管理页面上导入CSV数据。为此,您需要添加一个指向更改Hero列表页面的链接,点击这个链接会跳转到上传页面。你需要编
- 前言这篇博客将介绍光流的概念以及如何使用 Lucas-Kanade 方法估计光流,并演示如何使用 cv2.calcOpticalFlowPy
- 随着互联网的快速发展和数据交换的广泛应用,各种数据格式的处理成为软件开发中的关键问题。JSON 作为一种通用的数据交换格式,在各种应用场景中