How to update HTML file using Python?

1.8k views Asked by At

Could you please help me out in updating the title section below from "Test App Name" to "Demo App" using Python?

<!DOCTYPE html>
<html lang="en" class="selector-17-1">
<head class="selector-17-2">
  <title class="selector-17-4">Test App Name</title>
</head>

Thanks

1

There are 1 answers

2
SirJoe On

This should work

first install dependencies:

pip install lxml
pip install beautifulsoup4

execute

from bs4 import BeautifulSoup

with open("yourfile.html", "r") as f:
    text = f.read()

soup = BeautifulSoup("lxml", text)
soup.title = "Demo App"

with open("mynewfile.html", "w") as f:
    f.write(str(soup))