网络编程
位置:首页>> 网络编程>> Python编程>> Python编写简单的HTML页面合并脚本

Python编写简单的HTML页面合并脚本

作者:pppploi8  发布时间:2022-08-13 09:13:07 

标签:Python],HTML,页面合并

最近写一个BootStrap页面...因为功能需要所以决定一个页面解决所有问题,然后用jQuery来动态显示功能....然而这样做的话页面会相当庞大,一堆隐藏模态窗口和功能div都堆在一起看起来挺难受的 

然后想了下就用Python写了个小脚本用来支持<include>标签,用处是合并外部html文件,来强行分文件编写单个庞大的HTML页面 

用了下感觉挺好用的,分享给大家 

使用方法: 

HTML中使用<include src="">标签来导入其他HTML代码。支持嵌套替换(如A页面嵌套B页面,B页面嵌套C页面)。但是请小心循环嵌套(A页面嵌套B页面,B页面嵌套A页面),会导致死循环
主页面为默认处理页面为index.html,生成合并页面为newhtml.html
具体代码如下 


import codecs
import webbrowser
import sys

charset = "utf-8" #文件编码

#读取text里的<include>标签及src属性中的文件,替换原标签
def replaceInclude (filename,text):
try:
 posA = text.find("<include")
 while posA!= -1:
  posC = text.find(">",posA)
  tag = text[posA:posC+1]
  posA = text.find("src=",posA)
  posA += 5
  posB = text.find("\"",posA)
  file = text[posA:posB]#获取src中的文件名
  print ("正在处理:",file)
  tmpFile = codecs.open(file,"r",charset)
  tmpText = tmpFile.read()
  tmpText = replaceInclude(file,tmpText)#递归处理文件嵌套后的include标签
  text = text.replace(tag,tmpText)
  tmpFile.close()
  posA = text.find("<include")
 return text;
except Exception as e:
 print ("错误:文件",filename,"中的",file,"处理失败!错误信息:\n",e)
 sys.exit(1)

readFile = codecs.open("index.html","r",charset)
writeFile = codecs.open("newhtml.html","w",charset)
try:
text = readFile.read()
text = replaceInclude("index.html",text)
writeFile.write(text)
webbrowser.open("newhtml.html")
finally:
readFile.close()
writeFile.close()</pre>
0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com