1

please I have a question that is probably an easy one especially for those of you expert of HTML. I basically have a python pandas dataframe 'df' and I convert it to a HTML document using the useful method:

html = df.to_html()
text_file = open('example.html', "w")
text_file.write(html)
text_file.close()

The problem I face is that I would need to add a paragraph (a simple sentence) before the table.

I tried to add the following code to my script:

title = """<head>
              <title>Test title</title>
            </head>
                """
    html = html.replace('<table border="1" class="dataframe">', title + '<table border="1" class="dataframe">')

but it doesn't seem to do anything, plus in reality what I would need to add is not a title but a string containing the paragraph information. Does anybody have a simple suggestion that doesn't involve using beautiful soup or other libraries? Thank you.

2 Answers 2

3

This code does pretty much what I needed:

html = df.to_html()
msg = "custom mesagges"
title = """
    <html>
    <head>
    <style>
    thead {color: green;}
    tbody {color: black;}
    tfoot {color: red;}

    table, th, td {
      border: 1px solid black;
    }
    </style>
    </head>
    <body>

    <h4>
    """ + msg + "</h4>"

end_html = """
        </body>
        </html>
        """

html = title + html + end_html

text_file = open(file_name, "w")
text_file.write(html)
text_file.close()
Sign up to request clarification or add additional context in comments.

Comments

2

You should consider using dominate. You can build html elements and combine raw html. As a proof of concept:

from dominate.tags import *
from dominate.util import raw

head_title = 'test' # Replace this with whatever content you like
raw_html_content = '<table border="1" class="dataframe"></table>' # Replace this with df.to_html()


print(html(head(title(head_title)), body(raw(raw_html_content))))

This will output:

<html>
  <head>
    <title>test</title>
  </head>
  <body><table border="1" class="dataframe"></table> </body>
</html>

Alternatively you can build the html with BeauitfulSoup. It a lot more powerful, but then you have to write a lot more code.

from bs4 import BeautifulSoup

raw_html_content = '<table border="1" class="dataframe"></table> '
some_content = 'TODO <a href="#">click here</a>'

soup = BeautifulSoup(raw_html_content, features='html.parser') # This would contain the table

paragraph = soup.new_tag('p') # To add content wrapped in p tag under table
paragraph.append(BeautifulSoup(some_content, features='html.parser'))

soup.append(paragraph)
print(soup.prettify())

This will output:

<table border="1" class="dataframe">
</table>
<p>
 TODO
 <a href="#">
  click here
 </a>
</p>

You can use python built in f-string to add replacement fields with variables. Simply add the character f at the start of the string and then pass in the variable wrapped in brace brackets. This makes the html easier to read and edit. The downside is that to display brace brackets within the content, you have to use double brace brackets (see thead below).

An example e.g:

main_content = '<table border="1" class="dataframe"></table>' # // df.to_html()
msg = "custom messages"
html = f"""
    <html>
    <head>
    <style>
    thead {{color: green;}}
    tbody {{color: black;}}
    tfoot {{color: red;}}

    table, th, td {{
      border: 1px solid black;
    }}
    </style>
    </head>
    <body>
    <h4>{msg}</h4>
    {main_content}
    </body>
    </html>
    """
print(html)

This will output:

<html>
<head>
<style>
thead {color: green;}
tbody {color: black;}
tfoot {color: red;}

table, th, td {
    border: 1px solid black;
}
</style>
</head>
<body>
<h4>custom mesagges</h4>
<table border="1" class="dataframe"></table>
</body>
</html>

4 Comments

Thank you @Greg for the solution. Would you know how to solve this problem without using the dominate package please?
I've updated above with BeauitifulSoup, which will do the job but you'll need to write a lot more lines of code.Especially if you need to build up html, head, title and body tag
Thank you Greg, the problem is that as stated in the original question, I cannot use BeautifulSoup. I found a very simple way to solve the problem and add some HTML code without the need of any library. I will share it below. Thanks anyway, much appreciated
Sorry I didn't notice the bit about not being able to use BeautifulSoup. Anyway I'm glad you found a solution. I've made one minor tweak to your script, which is to use f-string to replace variables, please see above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.