tushariyer
tushariyer

Reputation: 958

Write HTML received as string to browser

I have a basic HTML file which looks like this:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome!</h1>
</body>
</html>

I am receiving the file in python and storing it as a string. I want to know, is there a way I can write this out to a web browser?

The file is on my computer, so my goal is not to save it as an html file and then execute it, but rather execute this from within python to the browser.

I know that with JavaScript I can use Document.write() to inject content to a webpage, but that is already being done in the browser. I want to achieve something similar.

Upvotes: 1

Views: 452

Answers (2)

Ajax1234
Ajax1234

Reputation: 71471

You can use flask, a simple Python web framework, to serve the string:

Using flask (pip install flask):

import flask
app = flask.Flask(__name__)
s = """
<!DOCTYPE html>
 <html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <h1>Welcome!</h1>
  </body>
 </html>
"""
@app.route('/')
def home():
  return s

if __name__ == '__main__':
    app.debug = True
app.run()

Now, can you navigate to 127:0.0.1:5000 or the equivalent IP and port specified when the app is run.

Upvotes: 2

briancaffey
briancaffey

Reputation: 2558

You could do the following:

html = """<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome!</h1>
</body>
</html>"""

with open('html_file.html', 'w') as f:
    f.write(html)

import webbrowser, os
webbrowser.open('file://' + os.path.realpath('html_file.html'))

Upvotes: 1

Related Questions