SoFunction
Updated on 2024-11-14

Python Write Simple HTML Page Merge Scripts

Recently wrote a BootStrap page... I decided to solve all the problems on one page because of the functionality needed, and then use jQuery to dynamically display the functionality .... However, this would make the page quite large, with a bunch of hidden modal windows and functional divs piled on top of each other.

Then I thought about writing a small script in Python to support the <include> tag, which is used to merge external html files to force a single huge HTML page to be written in separate files.

I've used it and feel it works well, I'll share it with you.

Usage: 

HTML using <include src=""> tags to import other HTML code. Nested substitutions are supported (e.g. page A nests page B, page B nests page C). But please be careful of circular nesting (page A nested page B, page B nested page A), it will lead to a dead loop!
The main page is the default processing page for, and the generate merge page is the
The specific code is as follows

import codecs
import webbrowser
import sys

charset = "utf-8" # Document encoding

# Read the <include> tag in text and the file in the src attribute and replace the original tag.
def replaceInclude (filename,text):
 try:
  posA = ("<include")
  while posA!= -1:
   posC = (">",posA)
   tag = text[posA:posC+1]
   posA = ("src=",posA)
   posA += 5
   posB = ("\"",posA)
   file = text[posA:posB]# Get the filename in src
   print ("Processing:",file)
   tmpFile = (file,"r",charset)
   tmpText = ()
   tmpText = replaceInclude(file,tmpText)# Recursively handle include tags after file nesting
   text = (tag,tmpText)
   ()
   posA = ("<include")
  return text;
 except Exception as e:
  print ("Error: file",filename,"in",file,"Processing failed! Error message:\n",e)
  (1)
   

readFile = ("","r",charset)
writeFile = ("","w",charset)
try:
 text = ()
 text = replaceInclude("",text)
 (text)
 ("")
finally:
 ()
 ()</pre>

This is the entire content of this article.