Python实现批量将word转html并将html内容发布至网站的方法
作者:爱兔一生 时间:2021-08-27 04:17:45
本文实例讲述了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,word,html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
从事设计行业的十年
2008-04-01 09:44:00
python3中rank函数的用法
2022-09-26 07:00:45
智能录入表格[适合BS模式项目的录入页面]
2008-03-09 19:02:00
Python OpenCV中的drawMatches()关键匹配绘制方法
2022-10-31 22:36:57
![](https://img.aspxhome.com/file/2023/1/110041_0s.png)
基于Python绘制520表白代码
2021-06-10 08:14:44
![](https://img.aspxhome.com/file/2023/6/64346_0s.png)
windows系统下让mysql支持federated的storage engine
2010-01-20 11:16:00
Numpy(Pandas)删除全为零的列的方法
2022-07-23 13:13:59
用python下载百度文库的代码
2023-07-31 00:40:44
Python实现Tracert追踪TTL值的方法详解
2023-06-24 13:08:14
![](https://img.aspxhome.com/file/2023/5/66405_0s.png)
OpenCV 图像梯度的实现方法
2023-07-14 08:25:43
![](https://img.aspxhome.com/file/2023/6/64296_0s.png)
Python3 利用requests 库进行post携带账号密码请求数据的方法
2023-04-03 05:37:53
Pytorch神经网络参数管理方法详细讲解
2023-04-04 14:07:26
Python 连接字符串(join %)
2021-01-13 23:30:46
浅谈java里的EL表达式在JSP中不能解析的问题
2023-06-20 11:55:05
快速实现基于Python的微信聊天机器人示例代码
2022-05-30 19:22:50
![](https://img.aspxhome.com/file/2023/4/121374_0s.png)
golang中的空slice案例
2023-09-02 12:26:36
![](https://img.aspxhome.com/file/2023/3/101043_0s.png)
python套接字流重定向实例汇总
2022-04-15 07:53:41
python起点网月票榜字体反爬案例
2021-03-11 02:56:05
![](https://img.aspxhome.com/file/2023/1/93441_0s.jpg)
Python如何实现强制数据类型转换
2022-10-18 10:08:02
网站LOGO设计规范的思考--1.设计基础
2007-10-14 10:55:00