Your translation script changes href="/help" into a translated phrase, splits “Read the shipping policy” around an inline link, and mangles {{ first_name }}. The common cause is treating HTML as text with boundaries a regular expression can recognize reliably. It cannot: attribute values, script content, and text between inline elements all have different structural roles.
Problem
Consider a shortcut that translates text inside quotation marks:
html = re.sub(r'"([^"]+)"', translate, html)
That expression has no way to tell whether a quoted string is an accessible label, a URL, a class name, a JavaScript value, or part of a template expression. A different pattern that targets text between tags has the opposite problem: inline markup divides a sentence into multiple matches. The phrase in <p>Read the <a href="/help">shipping policy</a> before ordering.</p> is not one uninterrupted text string in the source. Translate each fragment independently and the result may be awkward or grammatically wrong.
HTML parsing is stateful. Quotes and unquoted attribute values, character references, and script contents are not interchangeable stretches of characters. The HTML Standard even names parse errors such as duplicate-attribute and unexpected-character-in-unquoted-attribute-value. A pattern that sees a quote or angle bracket and assumes it found a boundary can mistake content for markup. Template tokens add another boundary: {{ first_name }} is meaningful to your application, but not an HTML element for a parser to protect automatically.
The key distinction is that parsing solves structure, not translation policy. A parser can identify an attribute or a text node; it cannot decide whether your application wants that value translated. You must define what stays untouched.
Fix
Parse the complete document with Beautiful Soup and explicitly select the text nodes your translation step is allowed to change. Using html5lib gives you a consistent HTML parsing choice, but parsing and serializing can normalize malformed markup. Keep the original file, write to a separate output, and review the result rather than expecting byte-for-byte preservation.
This small traversal leaves attributes alone, skips protected elements and anything inside them, and refuses to translate a text node containing a template token. The last rule is deliberately conservative: it preserves the whole node rather than risking damage to the token.
import re
from bs4 import BeautifulSoup, Comment
SKIP_TAGS = {"script", "style", "template", "code", "pre", "textarea"}
TOKEN = re.compile(r"\{\{|\{%|\*\||\$\{")
def inside_protected_element(node):
parent = node.parent
while parent is not None and getattr(parent, "name", None) != "[document]":
if parent.name in SKIP_TAGS:
return True
if parent.get("translate", "").lower() == "no":
return True
parent = parent.parent
return False
def translate_document(markup, translate_text):
soup = BeautifulSoup(markup, "html5lib")
for node in list(soup.find_all(string=True)):
if isinstance(node, Comment):
continue
text = str(node)
if not text.strip() or inside_protected_element(node) or TOKEN.search(text):
continue
node.replace_with(translate_text(text))
return str(soup)
Pass your translation function as translate_text; keep provider calls out of the traversal so you can test the selection rules without making requests. The traversal intentionally does not inspect or edit attributes. If you later decide to translate values such as alt or aria-label, handle those through a separate, explicit allowlist. Leave routing and styling values such as href, class, and id untouched by default.
Production rule: never send identifiers, URLs, or template syntax to a translation provider as ordinary prose and assume it will return them unchanged.
There is one important tradeoff in this example. If a text node contains both translatable copy and a token—“Hello, {{ first_name }}!”—the conservative rule leaves the entire node alone. Translating the surrounding words while preserving the token requires a placeholder-aware workflow: replace protected tokens with controlled placeholders, verify they survive the provider response, then restore them. Do not solve that case by removing the token and hoping the translated sentence still fits.
Also, do not try to speed this up by asking Beautiful Soup to partially parse only selected text. Its SoupStrainer partial-parsing feature does not work with html5lib. Parse the whole document, then apply skip rules while traversing it. For the broader translation workflow, see the full BeautifulSoup translation walkthrough; the translation project repository is useful context for keeping extraction and translation policy separate.
Finally, test with a small fixture that includes an inline link, a protected element, an attribute, and a template token. Assert both sides of the contract: intended text changes, while the URL, identifier, protected content, and token remain intact. A parser gives you a tree to work with; those checks ensure your edits respect the boundaries your application actually cares about.
Top comments (0)