Parsing HTML Is Not the Same as Displaying It Safely

When you have successfully parsed a section containing <img src=x onerror=alert(1)> When the string is deserialized, this malicious code remains intact in the o

Parsing HTML and displaying it safely are two separate jobs, and mixing them up is a common source of security problems in document pipelines. This guide is for developers and localisation teams who pull HTML from external sources into a preview, an internal system, or a translated deliverable.

The core problem is that a parser can read malicious markup without removing it. A string such as <img src=x onerror=alert(1)> survives parsing intact, and the dangerous attribute stays in the output. You will learn why BeautifulSoup alone does not protect you, how to test boundary inputs, and how to set acceptance criteria that tell automated processing apart from cases that need a person to review them.

This paper uses synthetic samples to demonstrate the processing method. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document.

Is a parser enough to make HTML safe? The short answer

No. BeautifulSoup parses markup and keeps hazardous attributes, so you need a separate whitelist-based sanitising layer before any external HTML reaches your system.

Your situationWhat to doWhy
You render external HTML in a previewApply a whitelist sanitiser before renderingParsing does not remove onerror or onclick attributes
You write HTML into a translated deliverableClean the content and check it against the acceptance checklistCleaning can change structure, so the output needs checking
A link uses data: or javascript:Remove the href valueExecutable content can hide in these URI schemes
The text shrinks sharply after cleaningMark the file for manual reviewExcessive stripping may remove structural information
You are unsure what to allowDefine the whitelist explicitlyA whitelist states what is allowed, which is safer than listing what is blocked

Why parsing is not sanitising

What BeautifulSoup is designed to do

  • The official documentation describes BeautifulSoup as “a library for extracting data from HTML and XML files”.
  • It provides methods for navigating, searching and modifying the tree, but it does not judge whether content is safe.
  • Given <a href="javascript:void(0)">Click</a>, BS4 builds a Tag object with the href attribute, but it does not decide whether that protocol should be permitted.

Why this neutrality is a risk

  • Tolerance helps: BS4 handles irregular legacy tags well.
  • Assumptions hurt: Developers who think “processed by BS4” means “sanitised” may render unverified HTML directly or write it into deliverables.
  • Real sanitising needs a whitelist: Only known-safe tag names, attribute names and value formats are kept after validation. Everything else is stripped.
  • This is your responsibility: A whitelist is not a built-in BS4 feature. You must add it as business logic on top of the parser.

Boundary inputs to test

The following inputs are synthetic. They demonstrate boundary conditions and do not reflect real traffic statistics or industry thresholds. If you need to test real documents, first remove personal information and sensitive links from the business data.

Correct input: <p>See <a href="https://example.com/doc">reference</a>.</p> The paragraph and link should be fully preserved, because p and a are on the whitelist and href uses HTTPS.

Boundary input 1: <div onclick="steal()">Safe text</div> The text is harmless, but onclick is an event handler attribute and must be removed entirely, leaving <div>Safe text</div>. If div is not on the tag whitelist, replace the whole tag with its plain text content.

Boundary input 2: <a href="data:text/html,<script>alert(1)</script>">Link</a> data: URIs can carry executable content. Even though the tag itself is valid, set the href value to null or delete it. A sanitiser cannot simply check for an http prefix; it must also confirm that the decoded content does not form a nested execution context.

These cases show that security decisions happen during attribute-level validation after parsing, not during parsing. BS4 turns strings into iterable objects, and the sanitising logic decides which objects may remain.

A whitelist sanitiser in memory

The following Python example shows the process in memory. It is for educational demonstration only. It does not handle multi-valued attributes, case normalisation, entity encoding or other details, and it must not be used directly in production. It depends on beautifulsoup4, which you must install yourself; locking the version is recommended. It makes no network requests and does not read or write files. The assertions express expected behaviour only; actual results depend on your environment and dependency versions.

# 教学示例:演示BS4配合白名单清洗原理,非生产级实现
from bs4 import BeautifulSoup, Comment
import re

ALLOWED_TAGS = {'p', 'a', 'b', 'i', 'ul', 'li'}
ALLOWED_ATTRS = {'href'}
SAFE_URL_PATTERN = re.compile(r'^https?://', re.IGNORECASE)

def sanitize_html(raw: str) -> str:
    soup = BeautifulSoup(raw, 'html.parser')
    # 移除注释
    for comment in soup.find_all(string=lambda t: isinstance(t, Comment)):
        comment.extract()
    # 遍历所有标签
    for tag in soup.find_all(True):
        if tag.name not in ALLOWED_TAGS:
            tag.unwrap()  # 保留子节点,移除标签本身
            continue
        # 清理属性
        attrs_to_remove = [k for k in tag.attrs if k not in ALLOWED_ATTRS]
        for attr in attrs_to_remove:
            del tag[attr]
        # 校验剩余安全属性值
        if 'href' in tag.attrs:
            href = tag['href']
            if not isinstance(href, str) or not SAFE_URL_PATTERN.match(href.strip()):
                del tag['href']
    return str(soup)

# 合成测试用例(仅用于理解原理)
safe = '<p>Hello <a href="https://ok.com">link</a></p>'
unsafe_event = '<p onclick="x()">text</p>'
unsafe_uri = '<a href="javascript:alert(1)">bad</a>'

assert sanitize_html(safe) == '<p>Hello <a href="https://ok.com">link</a></p>'
assert 'onclick' not in sanitize_html(unsafe_event)
assert 'href' not in sanitize_html(unsafe_uri)

In production, consider a dedicated sanitising library such as bleach, and move the whitelist configuration into external settings. The key principle is that the cleaning logic must state explicitly what is allowed, rather than try to list what is prohibited.

Acceptance criteria and manual review triggers

Code assertions can only confirm that predefined rules are enforced. They cannot cover every real-world exception. The table below lists typical scenarios from document processing, with the handling decision for each. It marks where automation should stop and a person should take over.

Observation of the phenomenonautomatic processing decisionWhether manual review is requiredNote
tag name is not on the whitelist but contains important textunwrap retained textnoensures no semantic loss
href is a relative path or mailto:removes the href attributeismay be a valid business link and requires manual confirmation
JS with HTML entity encoding in attribute valuesReject by string matchingisneeds to be verified whether it is a false positive
nested too deeply, causing parsing to time outtruncates or skips this fragmentisprevents DoS, but may drop content
The text length drops sharply after cleaning >30%is marked as suspiciousismay excessively strip structural information

A passing code demonstration does not mean end-to-end results are trustworthy. A “Yes” in the table means the automated process should pause and go to human review. In translation delivery, over-cleaning can break glossary references or invalidate formatting conventions.

References and next steps

Follow these steps before you decide whether to add this to your translation workflow:

  1. Run the synthetic example in a dependency environment with locked versions, and confirm that the basic cleaning logic behaves as expected.
  2. Prepare an HTML sample that contains real business tags.
  3. Test the sample item by item against the acceptance checklist.
  4. Record the ratio of automated processing to manual review.

Using this checklist for document translation

Process the body text, links and code of a web document separately. Put the protected sections on the acceptance checklist, then check the readability and page display after translation.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.

🎯 Which approach fits you?

If you render external HTML in a browser preview

Add a whitelist sanitiser before rendering, and treat parsing alone as insufficient.

If you deliver translated HTML content

Clean the markup, then use the acceptance checklist and manual review triggers before you release the file.

If your documents contain links or data: URIs

Check every href against the rules above and remove any that could carry executable content.

❓ FAQ

1. Does BeautifulSoup remove dangerous HTML attributes?

No. BeautifulSoup parses and modifies the tree, and it keeps attributes such as onerror unless your own logic removes them.

2. Is a whitelist better than a blacklist?

The article recommends a whitelist, because it states explicitly what is allowed. Trying to enumerate every prohibited pattern is harder to get right.

3. Can I use the example code in production?

No. The example is for educational demonstration only and omits several details, so it must not be used directly in production.

4. When should a person review the output?

Review it when a tag is not on the whitelist but holds important text, when a link is relative or uses mailto:, when entity-encoded JavaScript is found, when parsing times out on deep nesting, or when text length drops by more than 30% after cleaning.

📝 Summary

A parser reads HTML but does not make it safe, so a whitelist sanitiser and an acceptance checklist must sit on top of it. Test your own samples before you rely on automated cleaning in a translation workflow.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29