Compile simple HTML page merging scripts and Python scripts in python
I recently wrote a BootStrap page... because the function needs to solve all the problems on a page, and then use jQuery to dynamically display the function .... however, in this case, the page will be quite huge. It looks quite uncomfortable to pile up a bunch of hidden modal windows and functional divs together.
After thinking about it, I wrote a small script in Python to support the <include> tag. It is used to merge external html files to forcibly compile a single huge HTML page by file splitting.
It's quite helpful to use it. I 'd like to share it with you.
Usage:
Use the <include src = ""> label in HTML to import other HTML code. Nested replacement is supported (for example, page A is nested with page B and page B is nested with Page C ). But please be careful when nesting cyclically (page A is nested with page B and page B is nested with page A), which will lead to an endless loop
The main page is the ingress processing page index.html, And the merged page is newhtml.html.
The Code is as follows:
Import codecsimport webbrowserimport syscharset = "UTF-8" # file encoding # Read the <include> label in text and files in the src attribute, replace the original tag 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] # obtain the file name print (" processing: ", file) in src tmpFile = codecs. open (file, "r", charset) tmpText = tmpFile. read () tmpText = replaceInclude (file, tmpText) # recursively process the nested include label text = text. replace (tag, tmpText) tmpFile. close () posA = text. find ("<include") return text; Skip t Exception as e: print ("error: file", filename, "in", file, "failed to process! Error message: \ 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>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.