Vishal Tyagi
Exit/

Translate HTML without breaking the DOM

5 min left

About this Codelab

What you'll build

A script that EN→HI translates visible HTML text and leaves tags alone.

What you'll need

Python 3, BeautifulSoup4, and a sample HTML file.

Duration: ~5 min4 stepsIntroUpdated 2023-03

Don’t treat HTML as a string

# ❌ this will corrupt markup
html.replace("Hello", "नमस्ते")

Parsers exist so you can operate on text nodes.

Walk only visible text

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.

Swap the translator

Dictionary libs work offline for demos. Neural APIs work better for prose — keep the DOM walk identical; only translate() changes.

When to stop

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.