Python編寫簡單的HTML頁面合并指令碼_python

來源:互聯網
上載者:User

最近寫一個BootStrap頁面...因為功能需要所以決定一個頁面解決所有問題,然後用jQuery來動態顯示功能....然而這樣做的話頁面會相當龐大,一堆隱藏模態視窗和功能div都堆在一起看起來挺難受的 

然後想了下就用Python寫了個小指令碼用來支援<include>標籤,用處是合并外部html檔案,來強行分檔案編寫單個龐大的HTML頁面 

用了下感覺挺好用的,分享給大家 

使用方法: 

HTML中使用<include src="">標籤來匯入其他HTML代碼。支援嵌套替換(如A頁面嵌套B頁面,B頁面嵌套C頁面)。但是請小心迴圈嵌套(A頁面嵌套B頁面,B頁面嵌套A頁面),會導致死迴圈
首頁面為預設處理頁面為index.html,產生合并頁面為newhtml.html
具體代碼如下 

import codecsimport webbrowserimport syscharset = "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>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.