Python Html

  1. Python Html Template
  2. Python Html /n
Create html with python

Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. And Python comes to the rescue when I don’t want to write entire HTML code by myself. Let’s see how I have used Python to create HTML code. This is a simple application where you can use Python for automation. Python Generate HTML Table. Being like any other developer, I don’t have patience. Reading the HTML file In the below example we make a request to an url to be loaded into the python environment. Then use the html parser parameter to read the entire html file. Next, we print first few lines of the html.

4.3.1. Dynamically Created Static Local Pages from Python¶

For the rest of this chapter, the example files will come from thewww directory under the main examples directory you unzipped. Iwill refer to example file there as “example www files”.

As the overview indicated, dynamic web applications typicallyinvolve getting input from a web page form, processing the inputin a program on the server, and displaying output to a web page.Introducing all these new ideas at once could be a lot to absorb,so this sectionuses familiar keyboard input into a regular Python programand then, like in the final version,processes the input and produces the final web page output.

Follow this sequence of steps:

  1. Open the example www file hello.html in your browser, to see whatit looks like.
  2. Change your browser view - for instance go back to the previouspage you displayed.
  3. Open the same hello.html file in Kompozer, if that works for you,or another editor that will show the html source, as discussed inHTML Source Markup.
  4. If using Kompozer, switch to the Source view (clicking the Source tab).Sometimes you will want to copy HTML text into a Python program.For instance, I selected and copied the entire contents of thehello.html source view and pasted it into a multi-line string inthe Python program shown and discussed below.
  5. Careful, note the change from past practice here: Start Pythonfrom inside the www directory. In Windows you may start Idle withthe IdleOnWindows shortcutthat I placed in the www directory, not the original exampledirectory.
  6. Open the www example program in an Idleedit window.
  7. Run it.

You should see a familiar web page appear in yourdefault browser (possibly not the one you have been using). Thisis obviously not a very necessary program, since you can selectthis page directly in your browser! Still, one step at a time: itillustrates several useful points. The program is copied below.Read it:

This program encapsulates two basic operations into the last twofunctions that will be used over and over. The first,strToFile, has nothing new, it just puts specified text in afile with a specified name. The second, browseLocal, does more.It takes specified text (presumably a web page), puts it in a file,and directly displays the file in your default web browser. It uses theopen function from the webbrowser module to start the newpage in your web browser.

The open function here requires the name of afile or URL. Since the page is automatically generated by the programfor one-time immediate viewing, it automatically usesthe same throwaway filename, tempBrowseLocal.htmlspecified as the default in the keyword parameter. If youreally want another specific, name you could pass it as a parameter.

In this particular program the text that goes in the file is justcopied from the literal string named contents in the program.

This is no advance over just opening the file in the browserdirectly! Still, it is a start towards the aim of creating webcontent dynamically.

An early example in this tutorial displayed the fixedHelloWorld!' to the screen. This was later modified to incorporate user input using the string formatmethod of Dictionaries and String Formatting,

Similarly, I can turn the web page contents into a format string,and insert user data. Load and run the www example

The simple changes from are marked at thebeginning of the file and shown below. I modified the web page textto contain ‘Hello, {person}!’ in place of ‘Hello, World!’,making the string into a format string, which I renamed to themore appropriate pageTemplate. The changed initial portion withthe literal string and and the main program then becomes

Now the line

incorporaties the person’s name into the contents for the web pagebefore saving it to a file and displaying it.

In this case, I stored the literal format string inside the Pythonprogram, but consider a different approach:

Load and run the www example program It behavesexactly like, but is slightly different internally -it does not directly contain the web page template string. Insteadthe web page template string is read from the filehelloTemplate.html.

Python Html

Below is the beginning of, showing the only newfunctions. The first, fileToStr, will be a standard functionused in the future. It is the inverse of strToFile.

The main program obtains the input. In this simple example, theinput is used directly, with little further processing. It isinserted into the web page, using the file helloTemplate.htmlas a format string.

Although helloTemplate.html is not intended to be viewed by theuser (being a template), you should open it in a browser or web editor(Kompozer or ...) to look at it. It is legal to create a web page in a webpage editor with expressions in braces embedded in it! If you lookin the source view in Kompozer or in a web source editor,you will see something similar tothe literal string in, except the lines are broken updifferently. (This makes no difference in the formatted result,since in html, all white space is considered the same.)

Back in the Normal mode in Kompozer, or in source mode for any html editor, add anextra line of text right after the line “Hello, {person}!”.Then save the file again (under the samename). Run the program again, and see that youhave been able to change the appearance of the output withoutchanging the Python program itself. That is the aim of using thetemplate html page, allowing the web output formatting to bemanaged mostly independently from the Python program.

A more complicated but much more common situation is where theinput data is processed and transformed into results somehow, andthese results, often along with some of the original input, areembedded in the output web page that is produced.

As a simple example, load and run the www example, which uses the template fileadditionTemplate.html.

The aim in the end of this chapter is to have user input come froma form on the web rather than the keyboard on a local machine, butin either case the input is still transformed into results and allembedded in a web page. To make parts easily reusable, I obtainthe input in a distinct place from where the input isprocessed. In keeping with the later situation with web forms,all input is of string type (using keyboard input for now).

Look at the program. You will see only a few new lines! Because ofthe modular design, most of the program is composed of recentstandard functions reused.

The only new code is at the beginning and is shown here:

The input is obtained (via input for now), and it is processedinto a web page string, and as a separate step it is displayed in alocal web page.

There are a few things to note:

  • All input is strings. Before the numerical calculations, thedigit strings must be converted to integers.
  • I do calculate (a very simple!) result and use it in the outputweb page.
  • Although it is not in the Python code, an important part of theresult comes from the web page format string inadditionTemplate.html, which includes the needed variable names inbraces, {num1}, {num2}, and {total}. View it in your browseror in a web editor.

When you write your own code, you might modify,or you can start from a stripped down skeleton in the example www folder,, with comments about whereto insert your special code.

We will examine the bottom part of the following diagram later.The top part outlines the flow of data from string input toweb page in your browser for a regular Python program likewhat we have been describing, with the processing outlined in themiddle line. The parts in the middle will be common to the laterclient/server program, that manges input and output with the bottom line,that we will discuss later.

Again, this last section was somewhat artificial. You are not in the endlikely to find such programs practical as end products. Howeversuch programs are reasonable to write and test and they include almost allthe code you will need for a more practical (but harder to debug)CGI program, coming next.... Quotient Web Exercise¶

* Save or Modify it todisplay the results of a division problem in a web page.As in the exercises in Chapter 1, display a full sentencelabeling the initial data and both the integer quotient and the remainder.You cantake your calculations from Quotient String Return Exercise.You shouldonly need to make Python changes to the processInput andmain functions. You will also need the HTML for the output pagedisplayed. Make a web page template file calledquotientTemplate.html and read it into your program.Turn in both and quotientTemplate.html.


  • Self-documenting data file
  • Putting it all together

Lesson Goals

This lesson takes the frequency pairs created in CountingFrequencies and outputs them to an HTML file.

Here you will learn how to output data as an HTML file using Python. Youwill also learn about string formatting. The final result is an HTMLfile that shows the keywords found in the original source in order ofdescending frequency, along with the number of times that each keywordappears.

Files Needed For This Lesson


If you do not have these files from the previous lesson, you candownload programming-historian-6, a zip file from the previous lesson

Building an HTML wrapper

In the previous lesson, you learned how to embed the message “HelloWorld!” in HTML tags, write the result to a file and open itautomatically in the browser. A program that puts formatting codesaround something so that it can be used by another program is sometimescalled a wrapper. What we’re going to do now is develop an HTML wrapperfor the output of our code that computes word frequencies. We’re alsogoing to add some helpful, dynamic metadata to supplement the frequencydata collected in Counting Frequencies.


The distinction between data and metadata is crucial to informationscience. Metadata are data about data. This concept should already bevery familiar to you, even if you haven’t heard the term before.Consider a traditional book. If we take the text of the book to be thedata, there are a number of other characteristics which are associatedwith that text, but which may or may not be explicitly printed in thebook. The title of the work, the author, the publisher, and the placeand date of publication are metadata that are typically printed in thework. The place and date of writing, the name of the copy editor,Library of Congress cataloging data, and the name of the font used totypeset the book are sometimes printed in it. The person who purchased aparticular copy may or may not write their name in the book. If the bookbelongs in the collection of a library, that library will keepadditional metadata, only some of which will be physically attached tothe book. The record of borrowing, for example, is usually kept in somekind of database and linked to the book by a unique identifier.Libraries, archives and museums all have elaborate systems to generateand keep track of metadata.

When you’re working with digital data, it is a good idea to incorporatemetadata into your own files whenever possible. We will now develop afew basic strategies for making our data files self-documenting. In ourwrapper, we want to include dynamic information about the file, such asthe time and date it was created, as well as an HTML title that isrelevant to the file. In this case we could just give it a nameourselves, but when we start working with multiple files, automaticallycreating self-documenting files will save a lot of time, so we’llpractice now. And for that, we’ll have to learn to take advantage of afew more powerful string formatting options.

Python string formatting

Python includes a special formatting operator that allows you to insertone string into another one. It is represented by a percent signfollowed by an “s”. Open a Python shell and try the following examples.

There is also a form which allows you to interpolate a list of stringsinto another one.

In these examples, a %s in one string indicates that another string isgoing to be embedded at that point. There are a range of other stringformatting codes, most of which allow you to embed numbers in strings invarious formats, like %i for integer (eg. 1, 2, 3), %f forfloating-point decimal (eg. 3.023, 4.59, 1.0), and so on. Using thismethod we can input information that is unique to the file.

Self-documenting data file

Let’s bundle some of the code that we’ve already written into functions.One of these will take a URL and return a string of lowercase text fromthe web page. Copy this code into the module.

We’re also going to want a function that takes a string of any sort andmakes it the body of an HTML file which is opened automatically inFirefox. This function should include some basic metadata, like the timeand date that it was created and the name of the program that createdit. Study the following code carefully, then copy it into the obo.pymodule.

Mac Instructions

If you are using a Mac, make sure you include the proper file path inthe filename variable on the 2nd last line to reflect where you’resaving your files.

Python Html Template

Windows Instructions


Note that this function makes use of the string formatting operatorabout which we just learned. If you are still having trouble with thisidea, take a look at the HTML file that opened in your new Firefox taband you should see how this worked. If you’re still stuck, take a lookat the

in the HTML file and trace back how the program knew to put the URL valuethere.

The function also calls the Python datetime library to determine thecurrent time and date. Like the string formatting operator %s, thislibrary uses the % as replacements for values. In this case, the %Y %m%d %H %M %S represents year, month, date, hour, minute and secondrespectively. Unlike the %s, the program will determine the value ofthese variables for you using your computer’s clock. It is important torecognize this difference.

This date metadata, along with the name of the program that called thefunction, is stored in the HTML title tag. The HTML file that is createdhas the same name as the Python program that creates it, but with a.html extension rather than a .py one.

Putting it all together

Now we can create another version of our program to compute frequencies.Instead of sending its output to a text file or an output window, itsends the output to an HTML file which is opened in a new Firefox tab.From there, the program’s output can be added easily as bibliographicentries to Zotero. Type or copy the following code into your texteditor, save it as and execute it, to confirm thatit works as expected.

Python Html /n

Use either obo.wrapStringInHTMLMac() or obo.wrapStringInHTMLWindows() as appropriatefor your system.

Note that we interspersed our word-frequency pairs with the HTML breaktag <br>, which acts as a newline. If all went well, you should seethe same word frequencies that you computed in the last section, thistime in your browser window.

Suggested Readings

  • Lutz, Learning Python
    • Re-read and review Chs. 1-17

Code Syncing

To follow along with future lessons it is important that you have theright files and programs in your “programming-historian” directory. Atthe end of each chapter you can download the “programming-historian” zipfile to make sure you have the correct code. If you are following alongwith the Mac / Linux version you may have to open the file andchange “file:///Users/username/Desktop/programming-historian/” to thepath to the directory on your own computer.

  • zip sync