Skip to content

fix(core): escape text and attribute values in flatten_dom_to_str - #430

Open
JYunth wants to merge 1 commit into
ServiceNow:mainfrom
JYunth:fix/flatten-dom-escape
Open

JYunth wants to merge 1 commit into
ServiceNow:mainfrom
JYunth:fix/flatten-dom-escape

Conversation

@JYunth

@JYunth JYunth commented Nov 17, 2026

Copy link
Copy Markdown

flatten_dom_to_str writes text nodes and attribute values out as-is, then re-parses the result with BeautifulSoup. So page text that looks like markup turns into real elements in the HTML observation, a " inside an attribute value splits it into bogus attributes, and CDATA content gets mangled. This picks up where #178 left off, with the before/after example and the test that were asked for there.

Before (prune_html(flatten_dom_to_str(...)) on the new test page):

<p bid="4" id="text-markup">
 Write
 <button onclick="go()">
  Go
 </button>
 in the template.
</p>
<button bid="6" hi="" id="attr-quotes" title="Say " value="" wave="">

and a CDATA section x < y && "z" > 1 (on an XHTML page) comes out as 1]]&gt;.

After:

<p bid="4" id="text-markup">
 Write &lt;button onclick="go()"&gt;Go&lt;/button&gt; in the template.
</p>
<button bid="6" id="attr-quotes" title='Say "hi" &amp; wave' value="">

and the CDATA text comes through as x &lt; y &amp;&amp; "z" &gt; 1.

The fix escapes text and CDATA content with html.escape(..., quote=False) and attribute values with html.escape(...). CDATA is printed as escaped text because the lxml HTML parser used here mangles <![CDATA[...]]> sections either way. (On HTML pages Chrome already turns CDATA inside SVG into plain text, so CDATA nodes only show up in XHTML/XML documents.)

Tests: test_dom_to_text_special_characters (text and attributes, checked on both the flatten_dom_to_str and prune_html output) and test_dom_to_text_cdata (XHTML page). Both fail on main and pass here. The existing observation tests are unchanged and still pass.

flatten_dom_to_str wrote text nodes and attribute values out as-is and then
re-parsed the result with BeautifulSoup. Page text that looks like markup
(e.g. a code sample) became real elements in the observation, a `"` inside
an attribute value split it into bogus attributes, and CDATA content was
mangled.

Escape text and CDATA content with html.escape(quote=False) and attribute
values with html.escape(). CDATA is now printed as escaped text, since the
HTML parser used here doesn't support CDATA sections.

Adds tests with an HTML page (text, attributes) and an XHTML page (CDATA).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant