Don’t treat HTML as a string
# ❌ this will corrupt markup
html.replace("Hello", "नमस्ते")
Parsers exist so you can operate on text nodes.
About this Codelab
A script that EN→HI translates visible HTML text and leaves tags alone.
Python 3, BeautifulSoup4, and a sample HTML file.
# ❌ this will corrupt markup
html.replace("Hello", "नमस्ते")
Parsers exist so you can operate on text nodes.
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("source/index.html", encoding="utf-8"), "html.parser")
for node in soup.find_all(string=True):
if node.parent.name in {"script", "style"}:
continue
text = node.strip()
if not text:
continue
node.replace_with(translate(text)) # your translator here
open("translated/index.html", "w", encoding="utf-8").write(str(soup))
[!CHECKPOINT] Round-trip sanity Diff tag structure before/after (
grep -o '<[^>]+>'). Counts should match. Only text should change.
Dictionary libs work offline for demos. Neural APIs work better for prose — keep the DOM walk identical; only translate() changes.
Static marketing pages: great. React SPAs: translate source strings or use real i18n. This tool is a scalpel, not a CMS.
Project notes: HTML Content Translator.