1

I'm trying to save Pandas DataFrame to html file with embedded JavaScript code for autorefreshing.

My code is:

import pandas as pd

html_string = """
<html>
  <head>
<script>
function timedRefresh(timeoutPeriod) 
{
  setTimeout("location.reload(true);",timeoutPeriod);
}
window.onload = timedRefresh(5000);

</script>

</head>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>
  <body>
    {table}
  </body>
</html>
"""


df1.to_html("/html/calls.html")
    with open('/html/calls.html', 'w') as f:
       f.write(html_string.format(table=df1.to_html(classes='mystyle')))

But i get error:

KeyError: 'setTimeout("location'

1 Answer 1

1

You need to escape the curly brackets of the JS function. Use double brackets {{}}

Ex:

html_string = """
<html>
  <head>
<script>
function timedRefresh(timeoutPeriod) 
{{
  setTimeout("location.reload(true);",timeoutPeriod);
}}
window.onload = timedRefresh(5000);

</script>

</head>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>
  <body>
    {table}
  </body>
</html>
"""
Sign up to request clarification or add additional context in comments.

Comments

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.