Generate Html code using python

Free Python Code - Aug 18 '23 - - Dev Community

In this post, I will share with you how to generate HTML code using Python. I will use a library called yattag. Install it from here:
pip install yattag

code


from yattag import Doc

doc, tag, text = Doc().tagtext()

with doc.tag('body') as body:
    with doc.tag('h1') as h1:
        text('this is h1')

    with doc.tag('h2') as h2:
        text('this is h2')


html = doc.getvalue()
print(html)

Enter fullscreen mode Exit fullscreen mode

result

<body><h1>this is h1</h1><h2>this is h2</h2></body>
Enter fullscreen mode Exit fullscreen mode

As you can see, the result is HTML code. You can open this page in your web browser.

I will save it and display this page in my browser.
using the webbrowser module


with open('index.html', 'a+') as f:
    f.write(html)
    f.close()

webbrowser.open('index.html')

Enter fullscreen mode Exit fullscreen mode

result

Image description

Now we're done 🤗

Don't forget to like and follow 🙂

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .