Mar 2023Automation1 min read

HTML Content Translator

Python utility that walks an HTML DOM with BeautifulSoup, translates visible text nodes (EN→HI), and leaves tags, attributes, and script/style alone.

Translate visible HTML text without destroying the markup

Python / BeautifulSoup

The trap

Diagram
script or styletext nodeHTML fileBeautifulSoupparse to DOMWalk everytext nodeCode tag?Left untouchedTranslateEN to HIreplace_within placeHTML file,markup intactRegex overthe raw stringBroken markup

Treating HTML as a string and running a translator over it breaks tags, attributes, and scripts. You have to parse a DOM and touch text nodes only.

soup = BeautifulSoup(open(input_file, encoding='utf-8'), 'html.parser')

for tag in soup.find_all(string=True):
    if tag.parent.name in ['script', 'style']:
        continue
    english_text = tag.text.strip()
    if english_text:
        tag.replace_with(translate(english_text))

Scope

A focused CLI for static HTML batches: dictionary-style EN→HI conversion that prints each pair as it goes, and leaves markup untouched.

Try this pattern when

You need offline, markup-safe text transforms (translate, censor, rewrite) and don’t want a full i18n framework.